2

I have a directory full of XML files that look like this, for which I want to change the value of the "offset" element number from 1 to some other number

$ cat my.xml
      <offset xmlns="">1</offset>

I wrote various combinations of this sed command, but nothing I tried runs without an error. I am pretty sure that I need to escape some of the characters, but those that I've tried always end in errors ("unexpected token", "unknown option", etc). I also tried without the -e flag, since it really isn't an expression.

sed -i -e s/<offset xmlns="">1</offset>/<offset xmlns="">99</offset>/ *.xml

Any help would be appreciated.

4

Try this,

$ sed 's~<offset xmlns="">1~<offset xmlns="">99~g' file
          <offset xmlns="">99</offset>

Use a different sed delimiter if the input contain slashes.

6

You don't need to use / in sed, you can use comma for example:

sed -i 's,<offset xmlns="">1</offset>,NEW_TEXT,' FILE
2

You don't usually need all of that in the s/earch/replace/ function itself, and can instead first /address/ then conditionally /s///. It can not only help with readablity and to avoid some of the issues you mention, there can be a performance increase as well:

sed '/offset xmlns=/s/>1</>99</'
1

Use a proper parser for XML files. For example, I'd use xsh and use the following script:

for my $file in { @ARGV } {
    open $file ;
    for //offset set . 1 ;
    save :b ;
}
  • Probably the most proper answer, but I don't have that installed on this host. – EdgeCase Jun 18 '14 at 13:25
0

I would replace the 17th character of the line, which contains the value:

sed -i 's/^\(.\{17\}\)./\1VALUE/' file.xml

Replace VALUE with the new value for <offset>. Eg.

sed -i 's/^\(.\{17\}\)./\18/' file.xml

to change it to 8.

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.