grep Command Notes and Examples


Tags:

                                  
grep [options] 'pattern' [file ...]

Option  Description
------  -----------

-c      print only a count of the matching lines
-h      print matching lines but not the filenames
-i      ignore case 
-l      print names of files with matching lines but not the lines
-n      prefix match with line number
-r      recursive
-s      suppress error messages 
-v      print all lines that DON'T match pattern

see Reqular Expressions Reference for info on regular expressions

regular expressions should be enclosed in single quotes to prevent the shell
from interpreting special characters

---------------------------------------------------------------------------------
examples
---------------------------------------------------------------------------------

---------------------------------------------------------------------------------
search a file for a simple text string:

grep teststring testfile

searches the file "testfile" for the string "teststring"

---------------------------------------------------------------------------------
search a file for string and show line number 

grep -n teststring testfile

searches the file "testfile" for the string "teststring" and also shows the
line number where the match was found

---------------------------------------------------------------------------------
search a file for a string at the beginning of a line
 
grep -n '^teststring' testfile

searches the file "testfile" for the string "teststring" only where it is at
the beginning of a line and shows the line number where that match was found

---------------------------------------------------------------------------------
search for a string at the end of a line

grep -n 'teststring$' testfile

searches the file "testfile" for the string "teststring" only where it is at
the end of a line and shows the line number where that match was found

---------------------------------------------------------------------------------
count number of lines

grep -c teststring testfile

prints the number of lines found that match the string "teststring" in the
file "testfile"


grep -c -v teststring testfile

prints the number of lines found that DO NOT match the string "teststring" in
the file "testfile"

---------------------------------------------------------------------------------
recursive grep with the find command

find . -type f -print | xargs grep -i [PATTERN]

searches for PATTERN in all files found recursively, starting in the current
directory

---------------------------------------------------------------------------------