NOTE: See also Notes on Formal Language
Most common use is for finding a particular word or short string in a file. This is analogous to searching for a Web document via Yahoo. The syntax is:
grep expression filename(s)For example, you might want to find all the lines of code in your C files which refer to a particular variable.
grep 'count' *.cHow can you learn about grep?
1. TRY IT!!
2. there is a link to documentation with many examples accessible via the 126 FAQ list
3. type (on a Unix machine):
man grepYou can copy the manual page for grep to a file using '>' and then print that file. You should learn some of the main options for grep.
Here's some hints and highlights about grep:
- use single quotes around the expression
- [ ]
- Meaning: one of (in range).
- Examples:
[a3][c5] => a or 3 followed by c or 5, so valid matches are ac,a5,3c,35 [a-z] => any lowercase character between a and z
- ^
- Meaning: 'not' if it's inside brackets. Otherwise, it indicates that whatever it precedes must be the first thing on a matching line.
- Examples:
[^ a b c] => matches any lines in which at least one character is not a, b, or c '^a' => matches any lines which start with an 'a'
- . (a period)
- Meaning: any single character (like a wildcard)
- Examples:
'^c.b' => matches lines that start with a c and have b as the third character '.' => matches any lines that have any characters
- *
- Meaning: zero or more of what precedes it
- Examples:
'^c.*b' => matches lines that start with c and have at least one b 'c.*b' => matches any lines that have a c followed by a b (not necessarily adjacent)
- +
- Meaning: one or more of what precedes it
- Examples:
'c+b' => matches lines with cb, ccb, cccb, ccccb, etc. as substrings 'c.+b' => matches lines with cab, caab, cadb, etc. but not cb
- ?
- Meaning: zero or one of what precedes it
- Examples:
'c.?b' => matches cb and cab but not caab (and other strings...)
- $
- Meaning: whatever precedes it must be the last thing on a matching line
- Examples:
'c.*b$' => matches any lines that have a c and end with a b '^c.*b$' => matches any lines that start with c and end with b
- |
- Meaning: or (in egrep or grep -E)
- Example:
x | y => matches lines with x or y
- ()
- Meaning: parentheses are used for grouping
- /
- Meaning: the backslash character is used for escaping characters with reserved meaning (like a period)
- {some number}
- Meaning: repeat the preceding expression a given number of times
- Examples:
c{3} => matches lines with 3 consecutive c's (bc){2} => matches lines with the pattern bcbc
- grep -i expression file
- by default, grep is case sensitive. The -i flag makes the match case insensitive
- grep -c expression file
- return only the number of matching lines, instead of printing them
- grep -v expression file
- return all lines in the file not matching the expression
Try it out for yourself or read about it in a UNIX reference guide.