简体   繁体   中英

How to use awk counting the number of specificed digit in certain column

How can I count the matched value in the certain column?

I have a file:(wm.csv)

I executed the command to get the targeted value in certain column: tail -n +497 wm.csv | awk -F"," '$2=="2" {print $3" "$4}' tail -n +497 wm.csv | awk -F"," '$2=="2" {print $3" "$4}'

then I get the following output data I want:

hit 2 hit 2 hit 2 hit 2 miss hit 2 hit 2 hit 2 hit 2 hit 2 hit 2 hit 2 incorrect 1 hit 2 hit 2 hit 2

I want to count the number of "2" in second column in order to do simple math like: total digits in column divided by total number of row. Specifically, in this case, it would looks like: 14 (fourteen "2" in second column) / 16 (total number of row)

Following is the command I tried but this does not work : tail -n +497 wm.csv | awk -F"," '$2=="2" {count=0;} { if ($4 == "2") count+=1 } {print $3,$4,$count }' tail -n +497 wm.csv | awk -F"," '$2=="2" {count=0;} { if ($4 == "2") count+=1 } {print $3,$4,$count }'

thanks

taking the posted data as input file

$ awk '$2==2{c++} END{print NR,c,c/NR}' file

16 14 0.875
awk  '($0 ~ "hit 2"){count += 1}  END{print count, FNR, count/FNR}' sample.csv
14 16 0.875

I use ~ to compare the whole line($0) matches "hit 2", if it is increase counter by 1. FNR is the file number of records which is the total line number.

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