Reputation: 6080
I have a file looks like
Old data
alireza,mahdi,alireza,mohammad
alireza,olivia,amireza,hasan
alireza,alireza,alireza,alireza
New data
0.54:30.36:N 0.54:32.31:N 0.54:30.36:Y
0.54:30.36:Y 0.54:32.31:N 0.54:30.36:Y
0.54:30.36:N 0.54:32.31:N 0.54:30.36:Y
0.54:30.36:N 0.54:32.31:N 0.54:30.36:N
and I would like to count number of say, "Y" per line,
so the output would be
1
2
1
0
so I can grep it like `"grep -w ':Y' myfile" but then I don't know how to count it ! since wc ...
**UPDATE I am sorry to change the data and possibly the pattern. I wanted to present a simple and understandable format which I was not successful. Again, I do apologize.
Upvotes: 0
Views: 101
Reputation: 204628
This is the idiomatic awk way to print how may times a RE occurs on each line:
$ awk '{print gsub(/:Y/,"")}' file
1
2
1
0
Upvotes: 6
Reputation: 123658
For your new data, you could simply change the field separator:
awk -F'[ :.]' '{for(i=1;i<=NF;i++) {if ($i=="Y") c++;}}{print c; c=0}' inputfile
or make use of a pattern to match against:
awk '{for(i=1;i<=NF;i++) {if ($i~/:Y$/) c++;}}{print c; c=0}' inputfile
Both would yield:
1
2
1
0
for your new input.
Old answer: You could use awk
:
awk -F, '{for(i=1;i<=NF;i++) {if ($i=="alireza") c++;}}{print c; c=0}' inputfile
For your sample input, it'd produce:
2
1
4
0
Upvotes: 0