Count b or B in even lines

Viewed 152

I need count the number of times in the even lines of the file.txt the letter 'b' or 'B' appears, e.g. for the file.txt like:

everyB or gbnBra
uitiakB and kanapB bodddB
Kanbalis astroBominus

I got the first part but I need to count these b or B letters and I do not know how to count them together

awk '!(NR%2)' file.txt
5 Answers
$ awk '!(NR%2){print gsub(/[bB]/,"")}' file
4

Could you please try following, one more approach with awk written on mobile will try it in few mins should work but.

awk -F'[bB]' 'NR%2 == 0{print (NF ? NF - 1 : 0)}' Input_file

Thanks to @Ed sir for solving zero matches found line problem in comments.

awk '!(NR%2)' file.txt | tr -cd 'Bb' | wc -c

Explanation:

  • awk '!(NR%2)' file.txt : keep only even lines from file.txt
  • tr -cd 'Bb' : keep only B and b characters
  • wc -c : count characters

Example:

With file bellow, the result is 4.

everyB or gbnBra
uitiakB and kanapB bodddB
Kanbalis astroBominus

In a single awk:

awk '!(NR%2){gsub(/[^Bb]/,"");print length}' file.txt

gsub(/[^Bb]/,"") deletes every character in the line the line except for B and b.

print length prints the length of the resulting string.

Here is another way

$ sed -n '2~2s/[^bB]//gp' file | wc -c
Related