100 Useful Command-Line Utilities

by Oliver; 2014

15. grep, egrep

Based off of An Introduction to the Command-Line (on Unix-like systems) - grep: grep is the terminal's analog of find from ordinary computing (not to be confused with unix find). If you've ever used Safari or TextEdit or Microsoft Word, you can find a word with ⌘F (Command-f) on Macintosh. Similarly, grep searches for text in a file and returns the line(s) where it finds a match. For example, if you were searching for the word apple in your file, you'd do:
$ grep apple myfile.txt          # return lines of file with the text apple
grep has many nice flags, such as:
$ grep -n apple myfile.txt       # include the line number
$ grep -i apple myfile.txt       # case insensitive matching
$ grep --color apple myfile.txt  # color the matching text
Also useful are what I call the ABCs of Grep—that's After, Before, Context. Here's what they do:
$ grep -A1 apple myfile.txt	# return lines with the match,
				# as well as 1 after
$ grep -B2 apple myfile.txt	# return lines with the match,
				# as well as 2 before
$ grep -C3 apple myfile.txt	# return lines with the match,
				# as well as 3 before and after.
You can do an inverse grep with the -v flag. Find lines that don't contain apple:
$ grep -v apple myfile.txt	# return lines that don't contain apple
Find any occurrence of apple in any file in a directory with the recursive flag:
$ grep -R apple mydirectory/	# search for apple in any file in mydirectory
grep works nicely in combination with history:
$ history | grep apple  # find commands in history containing "apple"
Exit after, say, finding the first two instances of apple so you don't waste more time searching:
$ cat myfile.txt | grep -m 2 apple
There are more powerful variants of grep, like egrep, which permits the use of regular expressions, as in:
$ egrep "apple|orange" myfile.txt  # return lines with apple OR orange
as well as other fancier grep-like tools, such as ack, available for download. For some reason—perhaps because it's useful in a quick and dirty sort of a way and doesn't have any other meanings in English—grep has inspired a peculiar cult following. There are grep t-shirts, grep memes, a grep function in Perl, and—unbelievably—even a whole O'Reilly book devoted to the command:

image
(Image credit: O'Reilly Media)

Tip: If you're a Vim user, running grep as a system command within Vim is a neat way to filter text. Read more about it in Wiki Vim - System Commands in Vim.

Tip: Recently a grep-like tool called fzf has become popular. The authors call it a "general-purpose command-line fuzzy finder".

<PREV   NEXT>