Sed append regex capture groups
Asked Answered
R

1

7

If someone can please assist, I'm trying to do a sed append using regex and capture groups but its not working fully:

echo "#baseurl=http://mirror.centos.org/centos/$releasever/contrib/$basearch/" | sed -re '/#baseurl=http:\/\/mirror.centos.org(.*)/a baseurl=https:\/\/10.10.10.10\ \1'
 #baseurl=http://mirror.centos.org/centos//contrib//
 baseurl=https://10.10.10.10 1

At the moment it is just giving the literal value 1 rather than the capture group.

It should give:

 #baseurl=http://mirror.centos.org/centos//contrib//
 baseurl=https://10.10.10.10/centos//contrib//

I have tried backslash parentheses as well but its not working. Please assist....as it is hurting my head now...

Retrogression answered 23/8, 2016 at 14:19 Comment(0)
R
8

You can only capture back-reference when using s (substitute) command in sed.

This should working:

s="#baseurl=http://mirror.centos.org/centos/$releasever/contrib/$basearch/"    
sed -r 's~#baseurl=http://mirror\.centos\.org(.*)~&\nbaseurl=https://10.10.10.10\1~' <<< "$s"

#baseurl=http://mirror.centos.org/centos//contrib//
baseurl=https://10.10.10.10/centos//contrib//
Reichstag answered 23/8, 2016 at 14:26 Comment(3)
Very nicely done (I +1'd before). Why is this that back-references are just to be used in substitute mode? I could not find a reference on this.Knifeedged
I believe other than substitute mode only /search/ allows use of regex and groups and as there is no replacement there we cannot use back-reference.Reichstag
Thanks, I did sed with s and did two capture groups (...(.*)) and just printed \1\nxyz\2 which is more or less the same as yours! Thanks anyway!Retrogression

© 2022 - 2024 — McMap. All rights reserved.