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 )