This page is still under development...

Linux Unix Grep Command

The name grep comes from a command used in one of the early Unix editors : the ed command g/re/p (globally search a regular expression and print). The command searched for a regular expression, and printed it out.

grep is a command line utility. It searches for lines (from one or multiple files) containing a specific string matching a regular expression and displays the resulting lines to the standart output. Grep uses regular expressions. For more details, refer to the Regular Expressions page

Structure

Options

-h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.

-o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

#Learning from examples

bash cat > planets.txt <<- EOF Mercury Messenger of the Roman gods 3,031 miles Venus Roman goddess of love and beauty 7,521 miles Earth 7,926 miles Mars Roman god of war 4,217 miles Jupiter Ruler of the Roman gods 86,881 miles Saturn Roman god of agriculture 74,900 miles Uranus Personification of heaven in ancient myth 31,763 miles Neptune Roman god of water 30,775 miles Pluto Roman god of the underworld, Hades 1,430 miles EOF

Searching for lines containing a specific string

Let's search the file planets.txt for lines containing the string "Roman":

grep "Roman" planets.txt
Mercury    Messenger of the Roman gods 3,031 miles 
Venus      Roman goddess of love and beauty 7,521 miles
Mars       Roman god of war 4,217 miles 
Jupiter    Ruler of the Roman gods 86,881 miles
Saturn     Roman god of agriculture 74,900 miles 
Neptune    Roman god of water 30,775 miles
Pluto      Roman god of the underworld, Hades 1,430 miles

The search pattern specified as an argument is case sensitive by default

grep "roman" planets.txt

No matching lines...

Case insensitive search is done when using grep -i

Let's add option -i to ignore case to our previous command line

grep -i "Roman" planets.txt
Mercury    Messenger of the Roman gods 3,031 miles 
Venus      Roman goddess of love and beauty 7,521 miles
Mars       Roman god of war 4,217 miles 
Jupiter    Ruler of the Roman gods 86,881 miles
Saturn     Roman god of agriculture 74,900 miles 
Neptune    Roman god of water 30,775 miles
Pluto      Roman god of the underworld, Hades 1,430 miles

Adding the option -v inverts the matching results and returns lines which do not match the pattern.

The "g" was an abbreviation for "global search."