the man page starts as follows...
SYNOPSIS
grep [OPTIONS] PATTERN [FILE...]
grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]
DESCRIPTION
grep searches the named input FILEs (or standard input if no files are named, or if a single hyphen-minus (-) is given as file name) for lines containing a match to the given PATTERN. By default, grep prints the matching lines.
In addition, two variant programs egrep and fgrep are available. egrep is the same as grep -E. fgrep is the same as grep -F. Direct invocation as either egrep or fgrep is deprecated, but is provided to allow historical applications that rely on them to run unmodified.
..
..
..
..till the end of the page
The following are some practical uses of grep from my own experience and some sourced from the net.
1. Search file contents
Search for the word PAGE (case sensitive) in the file application.xml;
$grep "PAGE" /opt/tomcat7/webapps.labs/primetest/WEB-INF/configs/application.xml
For case insensitive match use the -i switch as follows;
$grep -i "PAGE" /opt/tomcat7/webapps.labs/primetest/WEB-INF/configs/application.xml
2. Search inside a directory
Search for the word drvierClassName inside the directory META-INF
$ grep -R "driverClassName" META-INF/
You will see result on a separate line preceded by the name of the file in which it was found.
3. Find whole words only
When you search for class, grep will match class, className etc.
$ grep -w "class" WEB-INF/context.xml
4. Multiple word search
Use the egrep command as follows:
$ egrep -w 'word1|word2' /path/to/file
5. Count occurences
The grep can report the number of times that the pattern has been matched for each file using -c (count) switch:
$ grep -R -c "driverClassName" META-INF/
6. Show line numbers
Pass the -n switch to precede each line of output with the number of the line in the text file from which it was obtained:
$
grep -R -n "driverClassName" META-INF/
7. Names of matching files only
Use the -l (list) switch as follows;
$ grep -R -l "driverClassName" META-INF/
8. Grep invert match
You can use -v option to print inverts the match; that is, it matches only those lines that do not contain the given word. For example print all line that do not contain the word bar:
$ grep -v bar /path/to/file
NB: for coloured output (if not on by default) you can add --color=auto to your grep command
Other options:
- -A x or -B x (where x is a number) --- display “x” lines After or Before the section where the particular word is found.