We're an ISO27001:2013 Certified Supplier

GNU 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.

No Comment

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

The ^ 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.

Look Around

It’s possible to output lines before or after a match with -B or -A respectively.

$ 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 -A and -B, there’s also -C: context.

$ grep -C 1 pattern file 
Still no match
This matches the pattern!
Later still: no match

Learn to count

Rather than piping grep into 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 other_file.

Eyeball it

The word 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!

Zipped lips

grep has a wrapper, zgrep, to grep through compressed files. Incredibly useful when checking a rotated-out log file, just call it like so:

zgrep pattern /path/to/file.gz

No gunzip needed!

Photo by Lars_Nissen_Photoart on Pixabay.

Leave a Reply

Your email address will not be published. Required fields are marked *

Secure. Reliable. Scalable.

If that doesn't describe your current Linux systems, check out our FREE Linux Survival Guide to help you get your systems up to scratch today!

  • This field is for validation purposes and should be left unchanged.