brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: grep -P uses Perl-compatible regular expressions

Linux
~/tips/tip-shell-grep-p-perl-regex

echo 'price=42 EUR' | grep -oP '\d+(?= EUR)'

Lets grep use Perl-style patterns such as lookahead and \d, which the basic and extended syntax lack.

Basic grep patterns get awkward fast. When I need a lookahead or a plain \d, I switch to Perl syntax.

echo 'price=42 EUR' | grep -oP '\d+(?= EUR)'
echo 'version=3.14' | grep -oP 'version=\K.*'

-P is short for --perl-regexp, and it makes grep treat the pattern as a Perl-compatible regular expression. The first example prints only 42: the number is matched, but only when it is followed by a space and EUR, and the lookahead part is not printed. With -o only the matching part is shown.

The second example uses \K, which drops everything matched so far from the output, so it prints 3.14. That is a neat way to pull a value out of a config line.

In grep -P, \d matches only the ten ASCII digits, whatever the locale, as the GNU manual points out.

The caveat is portability. -P is a GNU grep option, and other grep implementations may not have it. I would not count on it in a script that has to run on macOS or a minimal system, so test it there. The manual also says grep applies a pattern to one line at a time, so multi-line patterns need -z, and the manual marks that combination as experimental.

Further reading: GNU grep manual: grep programs

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link