How to search/grep

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

[edit] 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

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

$ ls | grep hello

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.

Personal tools