elpasso
elpasso

Reputation: 99

sed used to replace text between some chars with new text

I have a question with I can't figure out.

I have in xml file something like this:

<tag desc="some desc can be different" dep="dep" >value</tag>

I wanna change this like using sed to:

<tag desc="NEW DESC" dep="dep" >value</tag>

My question is: can I use sed to replace text between "<tag ... >" with new one?

Thank you for help :)

Upvotes: 0

Views: 113

Answers (2)

elpasso
elpasso

Reputation: 99

Thanks for quick answer :)

I have done something like this:

typeset repTagdesc='desc="NEW DESC" dep="dep"'
sed -i "s&\(<tag\).*\(>.[0-9]\)&\1 ${repTagdesc}\2&" input.xml

Is this solution OK? I am not familiar with sed, thats why I am asking. I check it and its works for:

<tag>10</tag>
<tag desc="some desc" dep="dep">20</tag>
<tag desc="other desc" dep="dep">30</tag>

Upvotes: 0

perreal
perreal

Reputation: 98118

Since you are not trying to really parse the xml sed can help you:

sed -i 's/\(<tag[^>]*[ ]*desc[ ]*\)=[ ]*"[^"]*"/\1="NEW DESC"/g' input.xml

But if you want to have a robust solution, use xmlstarlet:

xmlstarlet edit -L -u "//tag/@desc" -v "NEW DESC" input.xml

Upvotes: 4

Related Questions