Filtering with grep

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

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 use grep to search the file for the word and:

 $ ​​grep​​ ​​'and'​​ ​​words.txt
 candy
 hand

This displays the two lines of the file that show the string you specified. You get both results because they contain the string and somewhere on the line. This is ...

Get Small, Sharp Software Tools now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.