ISO27001:2013
Certified Supplier

FIND OUT MORE

We're an ISO27001:2013 Certified Supplier

blog-post-featured-image

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:

However, this will also remove any lines with inline comments, like this:

Adding some anchors to your commands will include lines with inline comments:

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:

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.

In addition to -A and -B, there’s also -C: context.

Learn to count

Rather than piping grep into wc or similar, use -c to count directly:

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:

No gunzip needed!

Feel free to contact us at info@tiger-computing.co.uk for more tricks with grep, or leave any you use in the comments below. We’d love to read them!

 

Photo by Lars_Nissen_Photoart on Pixabay.

Leave a Reply

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