4

I need to print the count of a matching string at the end of each line.

An example for matching foo:

foo,bar,foo,foo
bar,foo,bar,bar
foo,foo,bar,bar

Result :

foo,bar,foo,foo,3
bar,foo,bar,bar,1
foo,foo,bar,bar,2

I have checked this link(How to count the number of a specific character in each line?) but no luck.

9

We can use awk with gsub to get the count of occurrence.

 awk '{print $0","gsub(/foo/,"")}' file

Output:

foo,bar,foo,foo,3
bar,foo,bar,bar,1
foo,foo,bar,bar,2
1

Perhaps with a mixture of bash and grep

$ while read -r line; do 
    echo -n "$line -> " 
    grep -o foo <<<"$line" | wc -l 
  done < /path/to/my-input-file

foo,bar,foo,foo -> 3
bar,foo,bar,bar -> 1
foo,foo,bar,bar -> 2
0

In case anyone also wanted something in Python. Specify the filename and the magic word to count over.

#!/usr/bin/python3
# magic_word_count.py
# Takes a filename and magic word and prints the number of times the word
# appears on each line of the file.
#
# ./magic_word_count.py myfile.txt foo
#
import sys 
filename = sys.argv[1]
magic_word = sys.argv[2]

with open(filename, 'r') as f:
    for line in f.readlines():
        words = line.strip().split(',')
        print(len([word for word in words if word == magic_word]))

Usage:

$ cat myfile.txt 
foo,bar,foo,foo
bar,foo,bar,bar
foo,foo,bar,bar

$ ./magic_word_count.py myfile.txt foo
3
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy