Examples

  1. grep "the cat" *.txt /*.bat

    This command searches the files in the current directory that end in .txt and the .bat files in the root directory for the string the cat. Only exact case matches are listed on standard output: occurrences of The cat and the Cat are not listed.

  2. grep -i "the cat" *.txt /*.bat

    This command is similar to the previous one except that it performs a case-insensitive search. Occurrences of The cat and the CAT would be listed in addition to any occurrences of the cat.

  3. grep -sn "the {1,}cat" *.txt

    This command searches all .txt files in the current directory and in all subdirectories (recursively) for the pattern. The pattern consists of the word the, followed by one or more spaces, and followed by the word cat. Therefore, it would match lines that contain the cat or the cat. The ``filename(linenumber) : '' string is prepended to each line of each file in which the pattern is found.

  4. grep -i "[a-z][a-z0-9_]{0,}(" *.c

    This command searches all .c files in the current directory for function prototypes and function declarations. The pattern matches any string that begins with a letter, is followed by zero or more letters, numbers, or underscores, and ends with an open parenthesis.

  5. foo | grep "&cont\."

    This command searches the output of foo for the ``&cont.'' string. Note that the period in the pattern was escaped with a backslash. The grep command would interpret the ``&cont.'' pattern as meaning the ``&cont'' string followed by any character.

  6. grep "^Usage$" *.doc

    This command searches all .doc files in the current directory for lines that consist of nothing but the string ``Usage''.

  7. grep "streams\[" *.c

    This command searches all C files in the current directory for lines that contain the "streams[" string. Note that the ``['' character has to be escaped in the pattern so that it is interpreted by grep as a bracket and not as the beginning of a set or range.

  8. grep -v "^$" *.doc

    This command searches all .doc files in the current directory and lists all lines that are not blank. Note that the ^$ pattern matches any blank line.