awk如何以40个为一组对行进行求和

时间:2017-08-17 03:01:18

标签: awk

我这里有一个csv文件有3个字段,在第三个字段我想将行分组不超过25个。
鉴于:
" CW-03&#34 ;;(PE.502); 24
" CW-04&#34 ;;(PE.501); 25
" CW-05&#34 ;;(PE.518,PE.518-1); 2
" CW-06&#34 ;;(PE.517); 1个
" CW-07&#34 ;;(PE.516); 3
" CW-08&#34 ;;(PE.515); 1个
" CW-09&#34 ;;(PE.514); 1个
" CW-10&#34 ;;(PE.513,PE.513-1); 23
" CW-11&#34 ;;(PE.512); 8
" CW-12&#34 ;;(PE.511); 1个
" CW-13&#34 ;;(PE.510); 3
" CW-14&#34 ;;(PE.509); 3
" CW-15&#34 ;;(PE.508,PE.508-1); 17
" CW-16&#34 ;;(PE.507); 1个
" CW-17&#34 ;;(PE.506); 1个
" CW-18&#34 ;;(PE.505); 1个
" CW-19&#34 ;;(PE.521,PE.569); 2
" CW-20&#34 ;;(PE.520,PE.568); 17
" CW-21&#34 ;;(PE.519,PE.567); 17
" CW-22&#34 ;;(PE.526,PE.526-1,PE.574,PE.574-1); 4
" CW-23&#34 ;;(PE.525,PE.573); 2
" CW-24&#34 ;;(PE.524,PE.572); 2
" CW-25&#34 ;;(PE.523,PE.571); 3
" CW-26&#34 ;;(PE.522,PE.522-1,PE.570,PE.570-1); 19个

期望的输出:
" CW-03&#34 ;;(PE.502); 24
" CW-04&#34 ;;(PE.501); 25
" CW-05&#34 ;; (PE.518,PE.518-1,PE.517,PE.516,PE.515,PE.514); 8
" CW-10&#34 ;;(PE.513,PE.513-1); 23
" CW-11&#34 ;; (PE.509,PE.510,PE.511,PE.512); 15

你能救我吗?

2 个答案:

答案 0 :(得分:1)

${interval}

使用以下命令

采用awk-script
$ cat awk-script
function print_line(str1,str2,sum)
{
  print str1 OFS "(" str2 ")" OFS sum  # print the format as your request
}
NR==1 {
  str1=$1                              
  str2=$3                              # Use the str2 to store the combined output for $3
  sum=$5                               # Use sum to store the sum of $5
  next
}
{
  sum+=$5
  if (sum>25){                         # If sum is greater than 25
    print_line(str1,str2,sum-$5)       # print the line in the desired format
    str1=$1                            # and reset the str1 to $1
    str2=""                            # str2 to ""
    sum=$5                             # sum to $5
  }
  str2=(str2?str2",":str2"")$3         # update the str2 based on if str2 is ""
}
END {
  print_line(str1,str2,sum)            # flush the final result
}

答案 1 :(得分:0)

awk 解决方案:

function loginCheck($user_id, $pass){
   //here goes code which checks if user_id & pass exists
   //store in $RESULT if exists
    if(!empty($result)){

        session_set_cookie_params(30, '/');
        ini_set('session.gc_maxlifetime', 30);
        $_SESSION['username'] = $user_id;
        $_SESSION['logged_in'] = true;
    }
}

输出:

awk 'BEGIN{ FS=OFS=";" }
     f{ if(c+$3 > 25) { gsub(/\),\(/,",",r); print r,c; f=c=0 } else { c+=$3; r=r","$2 } }
     !f && c<25{ f=1; c=$3; r=$1 FS $2 }
     END{ if(c) gsub(/\),\(/,",",r); print r,c }' file