简体   繁体   中英

sed to find and replace a value in xml file

I have to run with sed for this job, without knowing the value (xxx), but only the attribute ( revision )

<types name="foo" revision="xxx">

to

<types name="foo" revision="5678">

my first try is:

sed 's@(revision=\").*@\1$5678\">@'

but it does not work.

You probably can get done with sed (in very simple cases) but for editing xml here are better (and error prone) tools, like xmlstarlet . Using it is simple:

xmlstarlet ed -u "//types/@revision" -v 5678 old.xml >new.xml

EDIT:

Alernative solution using perl & XML::LibXML module:

perl -MXML::LibXML -E '$d=XML::LibXML->load_xml(location=>q{file.xml});$_->setAttribute(q{revision},4567)for$d->findnodes(q{//types[@revision]});say $d'

Use the following sed approach:

sed -Ei 's~( revision=")[^"]+"~\15678"~g' test.xml

-E option, allows extended regular expresssion

-i option, allows modifying the file in place

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