Open System Services Shell and Utilities Reference Manual (G06.27+, H06.04+)
User Commands (g - j) grep(1)
EXAMPLES
1. To search several files for a string of characters, enter:
grep -F ’strcpy’ *.c
This command searches for the string strcpy in all files in the current directory with
names ending in .c.
2. To count the number of lines that match a pattern, enter:
grep -c -F ’{’ pgm.c
grep -c -F ’}’ pgm.c
This command displays the number of lines in pgm.c that contain left and right braces.
If you do not put more than one { or } on a line in your C programs, and if the braces are
properly balanced, then the two numbers displayed will be the same. If the numbers are
not the same, then you can display the lines that contain braces in the order that they
occur in the file with the command:
grep -n -E ’{}’ pgm.c
3. To display all lines in a file that begin with an ASCII letter, enter:
grep ’ˆ[a-zA-Z]’ pgm.s
Note that because the command grep -F searches only for fixed strings and does not
interpret pattern-matching characters, the following command searches only for the
literal string ˆ[a-zA-Z] in file pgm.s:
grep -F ’ˆ[a-zA-Z]’ pgm.s
A space character is required between the -F flag and the literal string specification.
4. To display all lines that contain ASCII letters in parentheses or digits in parentheses
(with spaces optionally preceding and following the letters or digits), but not letter-digit
combinations in parentheses, enter:
grep -E \
’\( *([a-zA-Z]*[0-9]*) *\)’ my.txt
This command displays lines file in my.txt such as (y) or ( 783902), but not (alpha19c).
Note that with the command grep -E, \( and \) match parentheses in the text and ( and )
are special characters that group parts of the pattern. With the grep command without
the -E flag, the reverse is true; use ( and ) to match parentheses and \( and \) to group
characters.
5. To display all lines that do not match a pattern, enter:
grep -v ’ˆ#’
This displays all lines that do not begin with a # (number sign).
6. To display the names of files that contain a pattern, enter:
grep -l -F ’rose’ *.list
This command searches the files in the current directory whose names end with .list and
displays the names of those files that contain at least one line containing the string rose.
A space character is required between the -F flag and the literal string specification.
527188-004 Hewlett-Packard Company 4−25