How to write noncapturing groups in egrep

2019-09-15 09:38发布

The following command does not correctly capture the 16714 from 16714 ssh -f -N -T -R3300:localhost:22

egrep -o '^[^ ]+(?= .*[R]3300:localhost:22)'

(However swapping to grep does if you use the -P flag. I was expecting egrep to be able to handle this)

标签: grep
2条回答
神经病院院长
2楼-- · 2019-09-15 10:05

To handle this with POSIX grep, you would use grep to isolate the lines of interest and then use cut to isolate the fields of interest:

$ echo "16714 ssh -f -N -T -R3300:localhost:22" | grep 'R3300:localhost:22' | cut -d' ' -f1
16714

Or, just use awk:

$ echo "16714 ssh -f -N -T -R3300:localhost:22" | awk '/R3300:localhost:22/{print $1}'
16714
查看更多
\"骚年 ilove
3楼-- · 2019-09-15 10:10

grep -P forces grep to use the Perl regexp engine.
egrep is the same as grep -E and it forces grep to use the ERE (extended regular expression) engine, that does not support lookahead.
You can find a quick reference of the differences between Perl and ERE (and others) here : http://www.greenend.org.uk/rjk/tech/regexp.html

查看更多
登录 后发表回答