Skip to main content

GREP

GREP

Grep is used to search file contents for a particular string or pattern.

grep [option] {search pattern} {filename}
Option Function
-i Case insensitive 
-v Exclude string
'string|string' OR Statement - used to search for multiple strings.
-r Recursive
-A & -B After & Before - used to specify a number of lines either before or after a specified string is found.
-E Extended Regular Expression.

Extended regular expression

Regular expression is essentially the methodology that we can use to manipulate grep to find advanced string patterns.

Special characters

When trying to grep for special characters, you need to make sure to 'escape' those characters, this is done by proceeding special characters with a \:

grep -E year\'s
Beginning and end of line

line begins with

The below example would show any lines beginning with the character '1'

grep -E "^1" filename

line ends with

The below example would show any lines ending with the character '1'

grep -e "1$" filename
Ranges

grep interprets ranges that are defined through square brackets []. 

line begins with 1 and is followed by numbers in the 0-2 range:

grep -E "^1[0-2]" filename

We can also search for ranges of letters

The below command would search for the letter b, proceeded by any letter in the specified range, followed by the letter g:

grep -E "b[aeiou]g" filename

We can also search a range of letters like this:

grep -E "b[a-z]g" filename

You can also combine ranges

grep -E "b[a-z,A-Z]g" filename
Wildcards

There are a number of wildcard options available to use in egrep.

. - any single character

grep -e "c.t" filename
  • Matches: "cat", "cot", "cut", etc.
  • Does not match: "ct", "caat"

* - matches zero or more occurrences of the preceding character

grep -e "g*d" filename
  • Matches: "gd", "god", "good", "goood"
  • Does not match: "go", "goooo", "gdo", "goddy"

.* - match zero or more of any character

grep -e "a.*b" filename
  • Matches: "ab", "acb", "axyzb", "a123b"
  • Does not match: "a b", "ab ", "acbd", "a"