Grep by Example
We are in the middle of a multipart series. Each post focuses on one member of the command-line text-processing trifecta: Grep, Sed and Awk. In this first part, we will explore Grep.
Grep stands for global regular expression print. As its name implies, it searches for text that matches a regular expression. In this post, we'll work through several examples.
Whenever "rhyme.txt" is referenced, assume it contains the following content:
Hickory dickory dock
The mouse ran up the clock
The clock struck one
The mouse ran down
Hickory dickory dock
-- "Hickory, Dickory, Dock" (public domain)
Example 1: Basic Search
The most basic use of Grep is to search for a word in a file:
grep "mouse" rhyme.txt
Which would produce the following output:
The mouse ran up the clock
The mouse ran down
Note that, by default, only lines that match the pattern are returned.
Example 2: Case Insensitive Search
To perform a case insensitive search, use the "-i" flag:
grep -i "MOUSE" rhyme.txt
Which would produce the same output as Example 1:
The mouse ran up the clock
The mouse ran down
Example 3: Line Numbers
To display line numbers in the output, use the "-n" flag:
grep -n "mouse" rhyme.txt
Which would produce:
2:The mouse ran up the clock
4:The mouse ran down
Example 4: Count Matches
To count the number of matching lines, use the "-c" flag:
grep -c "mouse" rhyme.txt
Which would output:
2
Example 5: Regular Expressions
Grep supports regular expressions. For example, to find lines that start with "The":
grep "^The" rhyme.txt
Which would output:
The mouse ran up the clock
The clock struck one
The mouse ran down
Example 6: Invert Match
To find lines that don't match a pattern, use the "-v" flag:
grep -v "mouse" rhyme.txt
Which would output:
Hickory dickory dock
The clock struck one
Hickory dickory dock
Example 7: Multiple Files
Grep can search multiple files at once:
grep "mouse" rhyme.txt poem.txt story.txt
When searching multiple files, Grep will prefix each match with the filename:
rhyme.txt:The mouse ran up the clock
rhyme.txt:The mouse ran down
poem.txt:The mouse was very quiet
story.txt:A mouse lived in the wall
Example 8: Recursive Search
To search all files in a directory (and its subdirectories), use the "-r" flag:
grep -r "mouse" .
This will search for "mouse" in all files in the current directory and its subdirectories.
Example 9: Context
To show lines before and after the match, use the "-A" (after) and "-B" (before) flags:
grep -A 1 -B 1 "struck" rhyme.txt
Which would output:
The mouse ran up the clock
The clock struck one
The mouse ran down
Example 10: Word Boundaries
To match whole words only, use the "-w" flag:
grep -w "the" rhyme.txt
This would match "the" but not "there" or "these".
Conclusion
These examples demonstrate the most commonly used features of Grep. In the next post, we'll explore Sed, which will allow us to not only search text but also modify it.