Skip to content

Lesson 16: Searching files with grep

You will often want to search files to find lines that match a certain pattern. The Linux command grep does this (and much more). The following examples show how you can use grep's command-line options to:

  • ignore case when matching (-i)
  • only match whole words (-w)
  • show lines that don't match a pattern (-v)
  • Use wildcard characters and other patterns to allow for alternatives (*, ., and [])

Navigate to directory ~/learning_linux/planets (make the directories if they do not exist) and add the following lines to 'earth.txt' using nano (or your favourite editor).

[learner planets]$ cat earth.txt
Earth is the only planet in the solar system that has life.
Earth is the only planet that has liquid water on its surface.
Earth is the only planet not named after a mythological god or goddess.
The highest point found on Earth is Mount Everest.
70% of the Earth’s surface is covered by water.

Let's run a few grepcommands to search 'earth.txt' for some patterns, from the planets directory.

[learner planets]$ grep planet earth.txt
[learner planets]$ grep -i WaTeR earth.txt
[learner planets]$ grep -v g.*s earth.txt
------------------------------------------------------------------------------------------------------------
Command                     Explanation                                                  Outcome Displayed
--------------------------- ------------------------------------------------------------ -------------------
`grep planet earth.txt`     Match all lines that include string 'planets'                Lines 1, 2 and 3
`grep -i WaTeR earth.txt`   Match all lines that include string 'water', ignoring case   Lines 2 and 5
`grep -v g.*s earth.txt`    Match all lines that do not contain the letter 's',          Lines 1, 2 and 5
                            followed by the letter 'g' anywhere on the same line
------------------------------------------------------------------------------------------------------------