Sasha
Sasha

Reputation: 29

Using Regex to search for several occurrences of a word

How do I search for x or more occurrences of a word using regular expressions and grep in a .txt file in a linux terminal, for example, find all lines with 4 or more "and"s in Sample.txt.

Upvotes: 2

Views: 107

Answers (2)

Bart Kiers
Bart Kiers

Reputation: 170158

Try this:

egrep "and(.*?and){3}" data.txt 

And to match "and" regardless of case ("And" or "AND", ...), but skip an "and" that is a part of another word (or name), try:

egrep -i "\band\b(.*?\band\b){3}" data.txt

The -i makes it ignore case, and the word boundaries, \b, will disregard occurrences like "Anand" and "Anderson".

Upvotes: 1

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136266

If you need to match and but not bandit, use something like the following:

egrep '\band\b(.+?\band\b){3}' Sample.txt

Upvotes: 0

Related Questions