On occasion you may need to find a file for which you do not know the name but you know the text in the file. In order to find a file by searching for text strings contained inside, use the grep command.

The grep command is used to search a file for a character pattern inside files and prints all lines that contain that pattern to the screen.

Tip: A string is one or more characters long; it can be a single character, a word, or a sentence. It can also include white space or punctuation.

Tip: grep is case sensitive unless the -i option is specified.

Command Format

grep [option(s)] string filename

Examples

To display the lines in the file accounting.txt that contain the word payroll:

$ grep payroll accounting.txt
Payroll is on the first and third Friday of every month.
$

You can also display a long listing of files in your home directory that changed on Oct 16th. A month name must be in its abbreviated form (e.g., Oct), and the single-digit dates must contain 2 spaces following month (e.g., Oct 1).

$ ls -la | grep 'Oct 16'
drwxr-xr-x 3 peanuts chuck 401 Oct 16 12:15
$