简体   繁体   中英

awk Count Zero and Non Zero field value:

Please help to identify , count of line items where Third field value is equal to Zero and count of line items where Third field value not equal to Zero , Group by Second field : Need to populate "Count!=0 & Count=0" as "0" if there is no count.

Input file: f1.txt
ppp1,abc,10,qqq
ppp2,abc,5,qqq
ppp3,abc,0,qqq
ppp4,abc,18,qqq
ppp5,abc,0,qqq
mmm1,xyz,0,rrr
mmm2,xyz,55,rrr
nnn1,ijk,12,sss
nnn2,ijk,89,sss
nnn3,ijk,62,sss
bbb1,lmn,0,ttt
bbb2,lmn,0,ttt

Output.txt
abc,count!=0,3
abc,count=0,2
xyz,count!=0,1
xyz,count=0,1
ijk,count!=0,3
ijk,count=0,0
lmn,count!=0,0
lmn,count=0,2

I break the cmd in lines, to make it easier to read:

 awk -F, -v OFS="," '{c[$2];
                    if($3!=0)a[$2]++;else b[$2]++}
                    END{for(x in c){
                         print x,"count!=0",a[x]*1;
                         print x,"count=0",b[x]*1}}' input

cat f1.txt | awk -F "," '{ if($3==0) {print $2 count=0} if ($3!=0)
{print $2 count!=0}}' | uniq -c | awk {print $2","$3","$1} >> Output.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM