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

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