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

share|improve this question

5 Answers 5

up vote 3 down vote accepted

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.

share|improve this answer

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

sed -i 's,<offset xmlns="">1</offset>,NEW_TEXT,' FILE
share|improve this answer

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 ;
}
share|improve this answer
    
Probably the most proper answer, but I don't have that installed on this host. –  EdgeCase Jun 18 at 13:25

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</'
share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

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

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