2016-08-20 96 views

回答

0

輸入

$ cat file 
a,x 
a,y 
a,z 
a,w 
b,x 
b,y 
a,x 
b,x 

輸出

$ awk 'BEGIN{FS=OFS=","}!(($1,$2) in b){b[$1,$2]; a[$1]++}END{for(i in a)print i,a[i]}' file 
a,4 
b,2 

可讀的版本

awk 'BEGIN{ 
       FS=OFS=","  # Set input and output separator 
      } 
!(($1,$2) in b){    # check index col1,col2 exists in array b 
       b[$1,$2]   # if not exists then its unique combination 
       a[$1]++   # set array b with index col1,col2 and increment count of array a 
      } 
     END{     # finally loop through array a and print contents 
       for(i in a) 
        print i,a[i] 
      }' file 
1

類似awk

$ awk -F, -v OFS=, '{a[$1]+=!b[$1,$2]++} END{for(k in a) print k,a[k]}' file 

a,4 
b,2 

另一種方法

$ sort -u file | cut -d, -f1 | uniq -c | awk '{print $2","$1}' 
相關問題