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, 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
- -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 with
- -R: go through directory recursively
- -E: use extended regular expression syntax.
- Fun fact:
g/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.