7

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?

zjeraar
  • 436
  • 4
  • 11
  • 1
    You almost have it, you just need the `sed 's/find/replace/` syntax: `sed 's/\(.*\)simple sample \(.*\) with \(.*\)/\1\2/' file`. I don't know why you are using `\c` by the way. – fedorqui Dec 16 '16 at 08:47
  • Yes, I know it is possible for this example, thanks. But the problem is that I need to replace the line, because I have regexes that I need to process that when they match the line, I only have the replacement value available. Ie. I might have a regex `simple sample` that if it matches should change the line to `great`. When I use you're method I would get `This is just a great line with some text`. I know this could be solved when the correct regexes would be put into place (in this case `(.*)simple sample(.*)`, but this is not possible due the the amount I have. I'm limited to `/c`. – zjeraar Dec 16 '16 at 08:59
  • 1
    Yeah you're right, I changed it. – zjeraar Dec 16 '16 at 09:08

2 Answers2

7

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.

Michael Vehrs
  • 3,293
  • 11
  • 10
  • 2
    Yeah :-). Could you explain a bit what is happening in the last section? – zjeraar Dec 16 '16 at 09:54
  • Ah I understand. Wonderful, didn't know about the ;. For people finding this, the part before the ; puts what we need on a new line and the part after the ; removes the first line. – zjeraar Dec 16 '16 at 10:05
1

Perl to the rescue!

perl -ne 'if (/(.*)simple sample (.*) with (.*)/) {
            print "$1$2\n";
          } else { print }'
choroba
  • 231,213
  • 25
  • 204
  • 289