Skip to content

grep

grep checks for matches per-line in a file or input stream and prints out matches, and is a standard tool in the linux admin's toolbox. It's easy to use, but there are some neat things you can do with it that aren't so obvious. This doc is mostly focused on the non-obvious things.

Unless specified, grep here means GNU grep. BSD (macOS) grep functions differently in many cases.

Examples

We use -E so we don't have to escape +.

$ echo 'Yummy fooood!' | grep -Eo 'fo+'
foooo

-P uses perl regex, which supports more features, like lookbehind. This lets us use -o but print only part of the string.

Use \K in place of lookbehind to trim the beginning of the match.

$ echo 'Yummy fooood!' | grep -Po 'foo\Ko+'
oo

Use lookahead to trim the end of the match

$ echo 'Yummy fooood!' | grep -Po 'foo(?=o+)'
foo

Here is a more practical example for determining the ip address of the interface that routes to your internet gateway:

$ ip -4 route get 8.8.8.8
8.8.8.8 via 192.168.1.1 dev eno1 src 192.168.1.234 uid 1000
    cache
$ ip -4 route get 8.8.8.8 | grep -oP 'src \K[\d.]+'
192.168.1.234

More info: https://www.regular-expressions.info/keep.html