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.

For search term, grep can take regular expressions rather than 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.

Options

Command-line options aka switches of grep:

Command-line options aka switches of GNU grep, beyond the bare-bones grep:

Links:

Regular expressions

Grep uses a particular version of regular expressions different from sed and Perl. Grep covers POSIX basic regular expressions (see also Regular Expressions/Posix Basic Regular Expressions).

Regular expression features available in grep include *, ., ^, $, [ ], [^ ], \( \), \n, \{i\}, \{i,j\}, \{i,\}.

Regular expression features available in GNU grep as a GNU extension include \?, \+, \b, \B, \<, \>, \w, \W, \s, \S.

Regular expression features available in grep with -E switch include ?, +, |, ( ), {i}, {i,j}, {i,}.

Predefined character classes supported by grep include [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:].

Regular expression features unavailable in grep include Perl's \d, \D, \A and \Z.

Links:

Examples

Examples of grep use:

Versions

Old versions of GNU grep can be obtained from GNU ftp server.

Release announcements of GNU grep are at a savannah group.

A changelog of GNU grep is available from git.savannah.gnu.org.

A version of GNU grep for MS Windows is available from GnuWin32 project, as well as from Cygwin.

See also

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.