Filtering with grep

Learn how to filter results with the grep command and regular expressions.

The grep command

When we’re dealing with program output, we often want to filter the results. The grep command lets us search the text for characters or phrases. We can use grep to search through program output or a file. Let’s explore grep by working with some files.

Execute the terminal below to create a file named words.txt that contains several words, each on its own line:

$ cat << 'EOF' > words.txt
> blue
> apple
> candy
> hand
> fork
> EOF

Now, we use grep to search the file for the word “and”:

$ grep 'and' words.txt

Run the complete code on the terminal below for practice.

cat << "EOF" > words.txt
blue
apple
candy
hand
fork
EOF
grep 'and' words.txt
Terminal 1
Terminal
Loading...

This displays the two lines of the file that show the string we specified. We get both results because they contain the string somewhere on the line. This is the simplest form of searching. Surrounding the search term in quotes isn’t always necessary, but it’s a good habit to get into because we can run into some strange edge cases with special characters if we don’t.

We can also tell grep to remove lines containing that text. The -v option instructs grep to only show lines that don’t contain the search pattern we specified.

Run the complete code on the terminal below for practice.

cat << "EOF" > words.txt
blue
apple
candy
hand
fork
EOF
clear
grep 'and' -v words.txt
Terminal 1
Terminal
Loading...

Processing the output of other programs

...