如果所有其他列都相同(AWK),则添加第一列

时间:2019-02-06 20:29:09

标签: awk

我有一个包含以下数据的文件:

25  POSIX shell script, ASCII text executable
25  POSIX shell script, ASCII text executable
3   PostScript document text conforming DSC level 3.0, type EPS, Level 2
2   PostScript document text conforming DSC level 3.0, type EPS, Level 2
23  PostScript document text conforming DSC level 3.0, type EPS, Level 2
4   SVG Scalable Vector Graphics image
4   SVG Scalable Vector Graphics image

,并且如果所有其他字段都相同,则希望对第一个字段求​​和,因此输出应为:

50  POSIX shell script, ASCII text executable
28  PostScript document text conforming DSC level 3.0, type EPS, Level 2
8   SVG Scalable Vector Graphics image

我尝试了这个awk命令:

awk '{ a[$2]+=$1 }END{ for(i in a) print a[i],i }' inputfile

打印:

25 POSIX
28 PostScript
8 SVG

但我找不到打印其余行的方法

3 个答案:

答案 0 :(得分:1)

这是一种方式:

$ awk '{v=$1;$1="";s[$0]+=v}END{for(i in s)print s[i] i}' file
8 SVG Scalable Vector Graphics image
50 POSIX shell script, ASCII text executable
28 PostScript document text conforming DSC level 3.0, type EPS, Level 2

解释:

$ awk '{
    v=$1              # store value in $1
    $1=""             # empty $1, record gets rebuilt
    s[$0]+=v          # sum indexing on $1less record
}
END {                 # in the end
    for(i in s)       # loop all 
        print s[i] i  # ... and output
}' file

答案 1 :(得分:1)

$ awk '{n=$1; sub(/[0-9]+ +/,""); a[$0]+=n} END{ for(i in a) print a[i],i }' file
28 PostScript document text conforming DSC level 3.0, type EPS, Level 2
50 POSIX shell script, ASCII text executable
8 SVG Scalable Vector Graphics image

答案 2 :(得分:1)

另一个“排序” awk

$  sort -k2 sergio.txt | awk  ' { t=$1; $1=""; c=$0;if(c==p) { s+=b} else { if(NR>1) print s+b,p; s=0} p=c;b=t} END { print s+b,p } ' sergio.txt
50  POSIX shell script, ASCII text executable
28  PostScript document text conforming DSC level 3.0, type EPS, Level 2
8  SVG Scalable Vector Graphics image
$

输入文件:

$ cat sergio.txt
25  POSIX shell script, ASCII text executable
25  POSIX shell script, ASCII text executable
3   PostScript document text conforming DSC level 3.0, type EPS, Level 2
2   PostScript document text conforming DSC level 3.0, type EPS, Level 2
23  PostScript document text conforming DSC level 3.0, type EPS, Level 2
4   SVG Scalable Vector Graphics image
4   SVG Scalable Vector Graphics image
$