简体   繁体   中英

Using sed to replace multiline xml

I'm trying to use sed to edit/change a xml file, but I'm having problems with multilines

The file I want to change has (extract)

<keyStore>
  <location>repository/resources/security/apimanager.jks</location>
  <password>wso2carbon</password>
</keyStore>

I want to change the password (and only the keyStore password, the file has another password tag)

I'm trying

sed -i 's/\(<keyStore.*>[\s\S]*<password.*>\)[^<>]*\(<\/password.*>\)/\1$WSO2_STORE_PASS\2/g' $WSO2_PATH/$1/repository/conf/broker.xml

but it's not working (change nothing, pattern not found) If I test the pattern in on-line tester ( https://regex101.com/ ) it seems to work find.

Also, I have tried to replace the [\\s\\S]* by [^]*, but in this case, sed generate a syntax error.

I'm using Ubuntu 16.04.1.

Any suggestion will be welcome

Parsing XML with regular expressions is always going to be problematic, as XML is not a regular language. Instead, you can use a proper XML parser, for example with XMLStarlet :

xmlstarlet ed --inplace -u "keyStore/password" -v "$WSO2_STORE_PASS" $WSO2_PATH/$1/repository/conf/broker.xml

Sed is not the tool for the job. Use an XML-aware tool, for example xsh :

open { shift } ;
insert text { shift } replace //keyStore/password/text() ;
save :b ;

Run as

xsh script.xsh "$WSO2_PATH/$1/repository/conf/broker.xml" "$WSO2_STORE_PASS"

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