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...

Jahed Uddin
  • 301
  • 1
  • 10

1 Answers1

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//
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    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. – fedorqui Aug 23 '16 at 15:33
  • 1
    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. – anubhava Aug 23 '16 at 15:40
  • 1
    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! – Jahed Uddin Aug 23 '16 at 15:45