Unix grep Command Notes and Examples

August 7, 2007 – 8:01 pm

 Tip courtesy of Kyle Reynolds at http://www.camelrichard.org

grep command notes and examples
——————————-

grep [options] ‘pattern’ [file …]

Option  Description
——  ———–
-i      Ignore upper/lower case distinction.
-n      Print matched lines and their line numbers.
-c      Print only a count of the matching lines.
-l      Print names of files with matching lines but not the lines.
-h      Print matching lines but not the filenames.
-v      Print all lines that don’t match pattern.
-s      Suppress error messages for non-existent or unreadable files.

Symbol          Meaning
——          ——-
^               Match the beginning of a line.
$               Match the end of a line.
[…]           Match one from a set of characters.
[^…]          Match any character not enclosed in brackets.
[n-m]           Match any characters in the range expressed by n-m.
.               Match any single character except a newline.
c*              Match any number of the preceding character, c.
.*              Match zero or more occurrences of any character.
\{n\}           Match exactly n occurrences of the preceding character or regular expression.
\{n,\}          Match at least n occurrences of the preceding character or regular expression.
\{n,m\}         Match any number between n and m of the preceding character or regular expression.
                Note: n and m must be between 0 and 256 inclusively.
\               Preceding any special character by a backslash (\) turns off the meaning.

Regular expressions should be surrounded by single quotes to prevent the shell from interpreting the
special characters.

EXAMPLES
=================================================================================

To search a file for a simple text string:

   grep copying help

This searches the file help for the string copying and displays each line on your terminal.

Search a file for string and output with line number

   grep -n setenv .tcshrc
   grep -n setenv *

Search a file for a string appearing at the beginning of a line

   grep -n ‘^setenv’ .tchsrc

Search for a string at the end of a line.

   grep -n ’setenv$’ .tcshrc

Count the number of lines in the file students that do not contain the string failing.

   grep -c -v ‘failing’ students

List all lines that contain a phone number of the form (nnn) nnn-nnnn.

   grep ‘([0-9]\{3\}) [0-9]\{3\}-[0-9]\{4\}’ afile

Save all lines from the file log that begin with error in a new file named problems.

   grep ‘^error’ log > problems

Count the number of users using the Korn shell.

   grep -c /bin/ksh /etc/passwd

————————————————————————–
Recursive Grep

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

Post a Comment