Searching the contents of a file: grep

To search a text file for a string of characters or a regular expression use the command:

   grep pattern filename(s)

Using this command you can check to see if a text file holds specific information. grep is often used to search the output from a command.

Examples

To search a file for a simple text string:

   grep copying help

This searches the file help for the string copying and displays each line on your terminal.

To search a file using regular expression:

   grep -n '[dD]on\'t' tasks

This uses a regular expression to find and display each line in the file tasks that contains the pattern don't or Don't. The line number for each line is also displayed. The expression is quoted to prevent the shell expanding the metacharacters [, ] and '. Double quotes are used to quote the single quote in dDon't.

To use the output of another command as input to the grep command:

   ls -l | grep '^d........x'

This lists all the directories in the current directory for which other users have execute permission. The expression is quoted to prevent the shell interpreting the ^ metacharacter.

To redirect the results of a search to a file:

   grep Smith /etc/passwd > smurffs

This searches the passwd file for each occurrence of the name Smith and places the results of this search in the file smurffs. There being a lot of Smiths everywhere this is quite a large file.

Using regular expressions with the grep command

The following characters can be used to create regular expressions for searching on patterns with grep. Always quote the regular expression. This prevents the shell from interpreting the special characters before it is passed to the grep command.

c

any non-special character represents itself

\\c

turns off the meaning of any special character

^

beginning of a line

$

end of a line

.

matches any single character except a newline

[...]

matches any of the enclosed characters

[^...]

matches any character that is not enclosed

[n-n]

matches any character in this range

*

matches any number of the preceding character

Examples

To search using enclosed characters:

   grep -n '[dD]on't' tasks

Finds and display each line in the file tasks that contains the pattern don't or Don't. The line number for each line is also displayed.

To search from the beginning of a line:

   ls -l | grep '^d........x'

This lists all the directories in the current directory for which other users have execute permission.

To search for lines ending in a particular pattern:

   ls -l | grep '[^.xdh]$'

This lists all the files and directories in the current directory which do not end in .xdh.