Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I developed a code which find and replaces a specific string in all xmls under all subdirectories. But i dont want all occurances to be replaced. In entire xml, code should find the tag xyz and replace xyz within this tag with abc. Other "xyz" in the xml should remain as it is. Can you please help me with this.

Thanks...

share|improve this question

2 Answers 2

You can use sed for the same

sed -i.bkp  5'i'"s/search/replace/"  inputfile
  • -i.bkp take backup as inpufile.bkp and edit original file
  • 5'i' go to line 5
  • s/ search and replace

also you can search specific word say 'NAME' and in same line search 'RAM' and replace with 'SHYAM' , see example below

sed -e '/NAME/s/RAM/SHYAM/g' filename

reference link

share|improve this answer
    
Using regex to manipulate XML will be fragile, there will always be edge-cases you can't account for. For anything more than the most trivial problems you are wiser to use an XML library with perl, python, etc. –  donothingsuccessfully Feb 17 '13 at 12:51
    
I think the OP is talking about a specific XML path rather than line number X. –  mtm Feb 17 '13 at 13:35

As mentioned by @donothingsuccesfully modifying xml with simple text replacement when you have requirements like tag xyz inside tag abc is generally a bad idea unless you have a very strict, known format of the input xml file, which is rarely the case. You need something that understands xml.

xml-sed from xml-coreutils allows you to run sed commands on an "echo-leaf" rather than a line which is basically means sed on an xml fragment with a PATH. So you would have something like

xml-sed 's/oldstring/newsting/' file.xml :/abc/xyz

Python lxml or Perl XML::Twig could be used if you can script it.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.