Grep
From Antalya
Main use
One of the most useful UNIX commands on the command line, grep basically prints lines that match a pattern. For example
grep error report.log
Will print every line in the file report.log that contains the string error. You can give multiple files, or use shell wildcards such as
grep error *.log
which will print every line that contains the string error in every file that ends with .log. If you want to catch lines that contain different combinations like Error, ERROR, ERRor, you can add the -i switch
grep -i error *.log
You can get very fancy with grep, the following uses a regular expression to match all lines that start with the word error (with alternatively some spaces before it).
grep -Ei "^\s*error" *.log
Common parameters
- -i: case insensitive match
- -v: print lines that do not match (invert matching)
- -n: print the line number that matched
- -w: the pattern must match a complete word (not only a part). i.e.
grep -w allwill not match a line withcall - -R: go through directory recursively
- -E: use extended regular expression syntax.
Tidbits
- Fun fact:
grepstands forg/re/pthis is the command sequence for global, regular expression, print in the original UNIX editor edlin, which basically prints every line in the file that matches the given regular expression.
- grep uses a simpler regular expression syntax. A more capable version called
egrepwas added later on. Modern implementations actually support both syntax. You can either callegreporgrep -Eto get the more powerful regular expression syntax.