Skip to main content
4 of 5
Show appreciation through votes. Thanks not necessary on SO/SX http://meta.stackoverflow.com/a/3021/186664
Anthon
  • 81.4k
  • 42
  • 174
  • 228

Using sed to find and replace complex string (preferrably with regex)

I have a file with the following contents:

<username><![CDATA[name]]></username> <password><![CDATA[password]]></password> <dbname><![CDATA[name]]></dbname> 

and I need to make a script that changes the "name" in the first line to "something", the "password" on the second line to "somethingelse", and the "name" in the third line to "somethingdifferent". I can't rely on the order of these occurring in the file, so I can't simply replace the first occurance of "name" with "something" and the second occurrence of "name" with "somethingdifferent". I actually need to do a search for the surrounding strings to make sure I'm finding and replacing the correct thing.

So far I have tried this command to find and replace the first "name" occurance:

sed -i "s/<username><![CDATA[name]]><\/username>/something/g" file.xml 

however it's not working so I'm thinking some of these characters might need escaping, etc.

Ideally, I'd love to be able to use regex to just match the two "username" occurrences and replace only the "name". Something like this but with sed:

<username>.+?(name).+?</username> 

and replace the contents in the brackets with "something".

Is this possible?

Harry Muscle
  • 2.7k
  • 2
  • 15
  • 8