Examples of using the grep command

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.


[Home] [Index]