用 sed 替换 xml 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23560215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
replace xml value with sed
提问by Vinod
I would like to replace value in XML file. Sample XML
我想替换 XML 文件中的值。示例 XML
<Console>
<!-- REQUIRED PARAMETERS -->
<!-- Enter the node that you are running the installation program from. This value must be a fully qualified name, which includes a host name and domain name. For example, node001.server.name.com.-->
<node>node.sample.ibm.com</node>
<!-- Enter the domain name of the cluster as a single dot-separated string. For example, server.name.com. -->
<sso-domain-name>sample.ibm.com</sso-domain-name>
<!-- Set this property to true if your InfoSphere BigInsights Console uses HTTPS. Otherwise, enter false. -->
<https>false</https>
<!-- management-console-port specifies which port is used by the Management Console. -->
<management-console-port>8080</management-console-port>
I would like to replace value. I tried with following but its not working. Any help appreciated.
我想替换价值。我尝试跟随但它不起作用。任何帮助表示赞赏。
sed -i "/<Console>/,/<\/Console>/ s/<node>[0-9][a-z]\+/<node>newvalue
回答by NeronLeVelu
sed -i -e '/<Console>/,/<\/Console>/ s|<node>[0-9a-z.]\{1,\}</node>|<node>newvalue</node>|g' YourFile
i assume value is between your tag and and only contain small letter, dot and digit (based on your sample and try). If extended, just add character missing in the class like [0-9a-z._-A-Z:]and maybe sub-class [:space:]
我假设值在你的标签之间,并且只包含小写字母、点和数字(基于你的样本并尝试)。如果扩展,只需添加类中缺少的字符,例如[0-9a-z._-A-Z:]子类 [:space:]
if newvalueis a variable content, dont forget to use double quote and escape character &, \and the separator of sed saction (default is /and |in my code)
如果newvalue是可变内容,不要忘记使用双引号和转义符&,\以及seds动作的分隔符(默认是/和|在我的代码中)
回答by BeniBela
You could use xmlstarlet:
你可以使用 xmlstarlet:
xmlstarlet ed -u //Console/node -v 'new value'
(Or something similar)
(或类似的东西)
回答by towi
Simple XML can be handled with the xml2suite quite well.
使用xml2套件可以很好地处理简单的 XML 。
You can translate an XML into a line-based format and work on that like you are used to. i.e.:
您可以将 XML 转换为基于行的格式,然后按照习惯进行处理。IE:
xml2 < x.xml | perl -pe 's|^(/Console/node=)(.*)$|newvalue|g' | 2xml > y.xml
I am not so versed in sedI am sure you can replace perlwith sedeasily.
我不太精通sed我相信你可以很容易地用sed替换perl。
回答by choroba
Use a proper XML parser. E.g., here is what I would do in xsh:
使用适当的 XML 解析器。例如,这是我将在xsh 中执行的操作:
open 1.xml ;
for //Console/node {
if xsh:matches(., '[0-9][a-z]+') set text() 'newvalue' ;
}
save :b ;

