The grep command can search for and list Linux files based on strings you are looking for and add the context of surrounding text.
The grep command can help you find Linux files containing the string you are looking for and even show you the text surrounding that string if you know a few tricks.
The first of these tricks allows you to create a list of files that contain whatever string you are looking for. It uses the -l (list just the file names, not the matched content) option plus the -r option for recursing through subdirectories. This can help you find files that you might be looking for without distracting you with all the reasons particular files matched your search criteria.
grep -rl “string you want to find” *
Example:
$ grep -rl "meeting minutes" * ARK2010/02-02-notes ARK2010/TBD Jan2010/TASkForce2 Mar2010/TaskForce2
Another useful trick with grep on Linux allows you to specify a Perl regular expression in your search term. In this example, we can give grep an expression that allows it to match on mulitple strings, much like egrep. You can get far more complicated than the examples shown, but here’s the basic syntax:
grep -P "while|for" * grep -P 'photo.gif' *
You can also combine grep with find commands to get some useful extractions of text from target files.
find . -name "*.r" -exec grep "rho" '{}' ; -print
Of course, one of the most useful grep tricks that I’ve come across so far is the one that provides some context along with your find. Instead of only displaying the lines containing the specific text you were searching for, you can print lines appearing before and after the matched lines — often required to determine whether tha “match” is really what you’re looking for.
You can specify how many lines you want to see before your matched string with the “B” (for “before”) option and the number of lines following the match with the “A” (for “after”) option.
$ grep -B 2 -A 2 echo *
--
while1-while [ $n -lt 5 ]
while1-do
while1: echo hello
while1- ((n +=1))
while1-done
--
whoison-#!/bin/bash
whoison-
whoison:echo hello, $USER
whoison:echo Look who is logged in!
whoison:echo ===========================
whoison-who | awk '{print $1}' | sort | uniq
whoison:echo ===========================
Notice that more than five lines were displayed in the second block of lines above because “echo” appeared more than once in these lines.
Read more on using grep:
- Taking advantage of the grep command’s many options
- 2 grep commands that will help you find whole words
- The many faces of the Linux grep command
- Making grep output easier to see
- Groping through big data with grep
- How to use the grep command
- How to use the grep command to cheat in Wordle: 2-Minute Linux Tips
- The best tools and techniques for finding data on Unix systems




