How To Search/grep

Grep is a Unix utility that searches through either information piped to it or files in the current directory. An example should help clarify things.

Let's say that we wanted to search through a directory, and wanted to find all the files that had the string "hello" in their name. You might issue the 'ls' command in a shell to list the directory's content and:

$ ls
DumpSite.sh  crontab.txt  nagios-3.0.6  xmpppy  xymon-4.3.0-beta2

and look through everything manually, or you could use the 'ls' command and pipe the output of ls to grep:

$ ls |grep crontab
crontab.txt

On the contrary, if you want to filter a list unless some entries, put it in the parameter -v:

$ ls |grep -v crontab
DumpSite.sh
nagios-3.0.6
xmpppy
xymon-4.3.0-beta2

the '|' character is the representation of the pipe basically directs the output of the 'ls' command as input for grep. You should get a nice (perhaps empty) list with all the files that have "hello" in their names.

If you know regular expressions, then you're in luck: grep can take regexes instead of just plain strings. A simple example for that might be looking for all .txt OR .jpg files in a directory :

$ ls | grep '.*[txt|jpg]'

The regex here is made up from .* which can stand for anything in a file's name and [txt|jpg] which yields either txt or jpg as file endings.

See also

  • zgrep (the same thing in some compressed files)
Last modified on 7 November 2010, at 03:16