Reputation: 169
I am trying to count occurrence of positive one (1) but I also have negative one (-1) in lines that's why its giving me cumulative count.
For example:
Script:
awk -F'|' 'BEGIN{print "count", "lineNum"}{print gsub(/1/,"") "\t" NR}' input_file
1 1 1 -1 -1 -1 0 0
-1 0 0 -1 -1 -1 0 0
1 1 0 -1 -1 -1 0 0
0 1 1 -1 -1 -1 0 0
Counts:
6
4
5
5
I am able to find count for only negative 1 (-1) using this command:
awk -F'|' 'BEGIN{print "count", "lineNum"}{print gsub(/\-1/,"") "\t" NR}' input_file
count for negative one (-1)
3
4
3
3
But unable to find desired count of only positive ones (1)
Desired count:
3
0
2
2
Any help will be highly appreciated.
Upvotes: 1
Views: 357
Reputation: 104024
With GNU awk, you can use word break assertions to definitively find -1
vs -11
(if those entries are possible.) Then use gsub
to get the count of the positive 1
remaining in the line:
echo "1 1 1 -1 -1 -1 0 0
-1 0 0 -1 -1 -1 0 0
1 1 0 -1 -1 -1 0 0
0 1 1 -1 -1 -1 0 0" >file
$ gawk '{gsub(/-1\>/,""); print gsub(/\<1\>/,"1")}' file
3
0
2
2
With POSIX awk, you can just loop the fields and check the values. Count them if it is what you seek:
$ awk '{cnt=0; for (i=1;i<=NF;i++) if ($i+0==1) cnt++; print cnt}' file
3
0
2
2
Upvotes: 1