3

So I'm trying to change two instances of a regex pattern to two different strings with sed like:

sed -E "s/\\t([A-Za-z]|[-])+$/\\t`get_addr.py -1`/" /path/to/file.ext
sed -E "s/\\t([A-Za-z]|[-])+$/\\t`get_addr.py -2`/" /path/to/file.ext

I've tried a lot of things, and done a solid amount of manpage scouring, but I just can't quite figure out how make it happen.

Is there a way I can tell sed to replace each match with a different string with something like

sed -E "s/\\t([A-Za-z]|[-])+$/[1st replacement],[2nd replacement]/" /path/to/file.ext

and/or is there a way I can specify in the regex that I'm looking for the nth match, so that I can just call sed twice?

3

At least in GNU sed, I think you can do something like

sed -e '0,/pattern/ s//replacement1/' -e '0,/pattern/ s//replacement2/' file

e.g. given a file

abc
def
abc
ghi
abc
jkl

then

$ sed -e '0,/abc/ s//XYZ/' -e '0,/abc/ s//UVW/' file
XYZ
def
UVW
ghi
abc
jkl
  • Awesome! Thank you! Totally got it to work. In my case I had to change the 0 in the second script to 2, like $ sed -e '0,/abc/ s//XYZ/' -e '2,/abc/ s//UVW/' file Not exactly sure why that is though, when I changed the 0 in the second script to 1, it overwrote both of the target texts with the second substitution, but when I changed it to 2, it worked as stated above. – blanket_cat Aug 24 '14 at 16:45
  • Hmm... in that case it's probably not working the way I thought - use with care. I'm sure one of the gurus will be along give a better solution soon. – steeldriver Aug 24 '14 at 16:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.