Using sed with special characters

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

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

Method 2

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.

Method 3

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</'

Method 4

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 ;
}

Method 5

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x