Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep shows occurrences of pattern on a per line basis

Tags:

linux

grep

bash

From the input file:

I am Peter
I am Mary
I am Peter Peter Peter
I am Peter Peter

I want output to be like this:

1 I am Peter
3 I am Peter Peter Peter
2 I am Peter Peter

Where 1, 3 and 2 are occurrences of "Peter".

I tried this, but the info is not formatted the way I wanted:

grep -o -n Peter inputfile
like image 467
Cindy Turlington Avatar asked Dec 24 '22 16:12

Cindy Turlington


1 Answers

This is not easily solved with grep, I would suggest moving "two tools up" to awk:

awk '$0 ~ FS { print NF-1, $0 }' FS="Peter" inputfile

Output:

1 I am Peter
3 I am Peter Peter Peter
2 I am Peter Peter

###Edit

To answer a question in the comments:

What if I want case insensitive? and what if I want multiple pattern like "Peter|Mary|Paul", so "I am Peter peter pAul Mary marY John", will yield the count of 5?

If you are using GNU awk, you do it by enabling IGNORECASE and setting the pattern in FS like this:

awk '$0 ~ FS { print NF-1, $0 }' IGNORECASE=1 FS="Peter|Mary|Paul" inputfile

Output:

1 I am Peter
1 I am Mary
3 I am Peter Peter Peter
2 I am Peter Peter
5 I am Peter peter pAul Mary marY John
like image 200
Thor Avatar answered Jan 05 '23 01:01

Thor