Comment

Comment by Calzifer

Since the list mentions grep -o (--only-matching) and regex. Here is my preferred trick to extract a specific part of a line and circumvent the lack of capture groups in grep.

Imagine you have a line containing

  prefix 1234 suffix
and want to only grep the number but need to match prefix and/or suffix to not grep another unwanted number.

Can be solved with

  grep --only-matching --perl-regexp 'prefix \K\d+(?= suffix)'
The magic is '\K' which kind of resets the 'matched buffer'. [1] So anything before \K is matched but not outputted with -o (or without -o anything before \K would not be highlighted).

And for the suffix: (?=) is a positive lookahead [2] which checks if, in this case, ' suffix' is found after the number but also does not include it in the 'matched buffer'.

So the output for

  echo "prefix 1234 suffix" | grep --only-matching --perl-regexp 'prefix \K\d+(?= suffix)'
is only

  1234
PS: instead of \K the prefix could also be wrapped in a positive lookbehind (?<=prefix )

[1] https://perldoc.perl.org/perlrebackslash#%5CK

[2] https://www.rexegg.com/regex-lookarounds.html

parent Calzifer 4 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton