Back to Posts Download PDF

Bash Tips and Tricks #2 - GREP

by Josh Kaplan, Jan 05, 2017

This is my second post with a handful of pastable commands to improve your use of Bash. If you haven’t seen the first post, you can check it out here. This one is all about GREP. the GNU Regular Expression Parser. A command line utility that has nearly infinite uses and applications.

Pastable #1

Grep for all the empty lines and count the number of lines.

grep "^$" <filename> | wc -l

wc is another command line utility that stands for “word count”. The -l option tells it to count the number of lines.

Pastable #2

Output only the number of lines that are matched.

grep -c "^$" <filename> 

Pastable #3

Get all the lines that don’t match the pattern.

grep -v "FindThisText" myfile.txt

The -v stands for invert.

Pastable #4

Recursive grep. This traverses the directory and subdirectories.

grep -R "^#" .

In this case, we’re finding every line in a shell script that starts with a comment. Grep is extemely powerful and you can do a lot more with it (perhaps I’ll do another post on it later). But you can always type man grep to see more options.

Pastable #5

If you want to include the lines around the matched lines try the following:

Use -A include N lines that come after the matched lines.

grep -A <N> "TODO" file.txt

Use -B include N lines that come before the matched lines.

grep -B <M> "TODO" file.txt

Or just use the -C option (for context) to include N lines before and after the matched pattern.

grep -C <N> "TODO" file.txt

Bonus

grep uses the Boyer-Moore algorithm to search for strings (source).