Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed capture group not working

This seems like one of the sipmlest possible examples of a sed capture group, and it doesn't work. I've tested the regex in online regex testers, and does what I want. At the linux command line it does not.

$ echo "a 10 b 12" | sed -E -n 's/a ([0-9]+)/\1/p'
$

and

$ echo "a 10 b 12" | sed -E -n 's/a ([0-9]+)/\1/p'
10 b 12

https://regex101.com/r/WS3lG9/1

I would expect the "10" to be captured.

like image 447
abalter Avatar asked Sep 01 '25 01:09

abalter


1 Answers

Your sed pattern is not matching complete line as it is not consuming remaining string after your match i.e. a [0-9]+. That's the reason you see remaining text in output.

You can use:

echo "a 10 b 12" | sed -E -n 's/a ([0-9]+).*/\1/p'
10

Or just:

echo "a 10 b 12" | sed -E 's/a ([0-9]+).*/\1/'
10
like image 166
anubhava Avatar answered Sep 02 '25 15:09

anubhava