The simplest use of grep is to
look for a pattern consisting of a single word.
It can be used in a pipe so that only those lines of the input files
containing a given string are sent to the standard output.
But let's start with an example reading from files:
searching all files in the working directory for a word--say,
Unix.
We'll use the wildcard * to quickly give
grep all filenames in the directory.
$ grep "Unix" *
ch01:Unix is a flexible and powerful operating system
ch01:When the Unix designers started work, little did
ch05:What can we do with Unix?
$
When grep searches multiple files,
it shows the filename where it finds each matching line of text.
Alternatively,
if you don't give grep a filename to
read, it reads its standard input; that's the way all filter programs
work:
$ ls -l | grep "Aug"
-rw-rw-rw- 1 john doc 11008 Aug 6 14:10 ch02
-rw-rw-rw- 1 john doc 8515 Aug 6 15:30 ch07
-rw-rw-r-- 1 john doc 2488 Aug 15 10:51 intro
-rw-rw-r-- 1 carol doc 1605 Aug 23 07:35 macros
$
First, the example runs ls -l to
list your directory.
The standard output of ls -l is piped
to grep, which only outputs lines that
contain the string Aug
(that is, files that were last modified in August).
Because the standard output of grep
isn't redirected, those lines go to the terminal screen.