Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed replace line with capture groups

Tags:

sed

Is it possible with sed to replace a line with capture groups from the regex?

I have this regex, please note that this is fixed, I cannot change it.

simple sample(.*)

This is what I want:

This is just a simple sample line with some text

Change to:

line with some text

I need something like this:

sed '/simple sample \(.*\)/c \1'

Which now outputs:

1

Anybody knows if you can use capture groups in sed with the change line function?

like image 797
zjeraar Avatar asked Dec 16 '16 08:12

zjeraar


1 Answers

Like this?

echo "This is just a simple sample line with some text" | \
  sed 's/simple sample \(.*\)/\n\1/;s/.*\n//'

The idea is simple: replace the whole regexp match with the captured group preceded by a newline. Then replace everything up to and including the first newline with nothing. Of course, you could use a marker other than the newline.

like image 54
Michael Vehrs Avatar answered Oct 21 '22 10:10

Michael Vehrs