Grep

From Antalya
Revision as of 22:05, 27 December 2020 by Kgf (talk | contribs) (Created page with "<div class="flex-row row"> <div class="col-xs-12 col-md-8"> <div class="panel panel-success"> <div class="panel-heading">'''Main use'''</div> <div class="panel-body"> One of...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
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 all will not match a line with call
  • -R: go through directory recursively
  • -E: use extended regular expression syntax.

Tidbits

  • Fun fact: grep stands for g/re/p this 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 egrep was added later on. Modern implementations actually support both syntax. You can either call egrep or grep -E to get the more powerful regular expression syntax.