简体   繁体   English

使用sed替换多行xml

[英]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 我正在尝试使用sed编辑/更改xml文件,但是多行出现问题

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) 我想更改密码(只有keyStore密码,该文件具有另一个密码标签)

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. 但它不起作用(不进行任何更改,找不到模式)如果我在在线测试仪( https://regex101.com/ )中测试模式,则似乎可以正常工作。

Also, I have tried to replace the [\\s\\S]* by [^]*, but in this case, sed generate a syntax error. 另外,我尝试用[^] *替换[\\ s \\ S] *,但是在这种情况下,sed会产生语法错误。

I'm using Ubuntu 16.04.1. 我正在使用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. 用正则表达式解析XML总是有问题的,因为XML不是正则语言。 Instead, you can use a proper XML parser, for example with XMLStarlet : 相反,您可以使用适当的XML解析器,例如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. Sed不是这项工作的工具。 Use an XML-aware tool, for example xsh : 使用支持XML的工具,例如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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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