grep, from globally search a regular expression and print, has a massive man-page and a full set of flags. It’s probably one of our favourite commands, between it’s sheer power and flexibility.
If you want to view a file without any comments, you can use
grep‘s inversions to do so:
grep -v '#' /path/to/file
However, this will also remove any lines with inline comments, like this:
# This is a comment variable = value; # This is an inline comment
Adding some anchors to your commands will include lines with inline comments:
grep -v '^#' /path/to/file
^ anchors to the start of the line, so any line where the first character is a
# will be hidden.
Indentation makes things a little trickier, but can be handled like so:
grep -v '^\s*#' /path/to/file
Any line where the first non-space character is a
# will be hidden. To make those changes permanent, see our other tip: Removing comments.
It’s possible to output lines before or after a match with
$ cat file No match Still no match This matches the pattern! Later still: no match No Match 4: The Fifth Line
$ grep -B2 pattern file No match Still no match This matches the pattern! $ grep -A2 pattern file This matches the pattern! Later still: no match No Match 4: The Fifth Line
In addition to
-B, there’s also
$ grep -C 1 pattern file Still no match This matches the pattern! Later still: no match
Learn to count
Rather than piping
wc or similar, use
-c to count directly:
$ grep -ci todo file 2 $ grep -cir todo directory/ directory/file:2 directory/other_file:4
There’s two to-do’s in
file, and four in
grep itself can be used as a verb, meaning ‘search for something’. While not really a Linux tip per se, a number of Linux-users will probably pick up on it. We often hear (and say!) that:
You can’t grep dead trees!
grep has a wrapper,
grep through compressed files. Incredibly useful when checking a rotated-out log file, just call it like so:
zgrep pattern /path/to/file.gz
Feel free to contact us at email@example.com for more tricks with
grep, or leave any you use in the comments below. We’d love to read them!