简体   繁体   中英

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 :)

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM