Skip to main content

grep

grep is cool; it allows us to search for text in various text files, including log files. However, grep has lots of little nuances and subtleties that need to be understood in order to maximize its utility as a program.

grep basics

Every grep search has the following structure:

grep [options] regex FILE

This specifies the command, takes into account any options, ingests the search term or regular expression supplied, and points to the file to search through.

A standard grep search looks like:

grep "<search term>" FILE

This is the most straightforward application of grep. It returns every line that contains the search term in the terminal. Regex can be substituted for the search term or combined with a search term to narrow down results.

There are various option flags that can be appended to the grep query

Option Description
-i The search will not distinguish between upper and lowercase characters (ignores case)
-v Instead of returning lines that match the search terms, grep will return those that do not (inverse match)
-c Instead of returning lines that match the search terms, grep prints how many lines matched the terms, or didn't, if used with -v (count)
-l (lowercase "L") Returns names of files that have contents that match the search terms
-L Returns names of files that have contents that do not match the search terms
-n Prefixes each returned line with the line number it occupies within the specified file
-h For mutli-file grep searches, prevents grep from printing filenames for each search
-B (capital "B") Show some number of lines before the matching line
-A (capital "A") Show some number of lines after the matching line
-C (capital "C") Show the same number of lines before and after the matching line

Things I had to do with grep

Searching For Two Words on the Same Line

A simple way to search for two words on the same line is to perform a pipe operation:

grep "word1" FILE | grep "word2"

The above searches the file for lines containing the first word, and then passes the results to the second grep operation which searches the results for lines containing the second word. However, extended grep (egrep or grep -E) can be used to avoid piping the results into a second grep, which is more efficient - useful for grepping through large files:

grep -E "word1.*word2|word2.*word1" FILE

Even better is that if we know that the line we're looking for will have "word1" before "word2" in every circumstance we're looking for, we can use regular grep with the above regex:

grep "word1.*word2" FILE