简体   繁体   中英

How do I replace atributes of XML file by using shell scripting sed command?

<?xml version='1.0' encoding='utf-8'?>
<widget id="io.ionic.starter" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
...
</widget>

How can I replace id and version in widget by using sed?

Sed is not the correct tool to handle XML, as the attributes might appear in different order and or different lines while still keeping the same semantics.

Use an XML aware tool. For example, in xsh (a wrapper around XML::LibXML currently maintained by me), you can just write

open file.xml ;
register-namespace w http://www.w3.org/ns/widgets ;
set /w:widget/@id "new.id" ;
set /w:widget/@version "0.0.2" ;
save :b ;  # :b creates a backup.

With xmlstarlet:

xmlstarlet edit -N x='http://www.w3.org/ns/widgets' \
                --update "//x:widget/@id" --value "foo" \
                --update "//x:widget/@version" --value "bar" file.xml

Output:

<?xml version="1.0" encoding="utf-8"?>
<widget xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0" id="foo" version="bar">
...
</widget>

If you want to edit file inplace, add option -L .

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