[英]Read and Modify the key value in XML using Bash/Shell script
I need to read (store in variable) and then change the online_hostname key value in XML using bash/shell script.我需要读取(存储在变量中),然后使用 bash/shell 脚本更改 XML 中的 online_hostname 键值。
<?xml version="1.0" encoding="UTF-8" ?>
<bzinfo>
<myidentity online_hostname="testdevice-air_2022_01_25"
bzlogin="me@abc.com" />
</bzinfo>
I am able to read the value but not able to change it.我能够读取该值但无法更改它。
cat test.xml | grep '<myidentity ' | sed -E 's/.*online_hostname="?([^ "]*)"? .*/\1/'
Please DO NOT use sed
to parse/edit XML .请不要使用sed
来解析/编辑 XML 。 Use an XML-parser instead.请改用 XML 解析器。
$ xidel -s input.xml -e '
x:replace-nodes(//@online_hostname,function($x){attribute {name($x)} {"newhost"}})
' --output-format=xml --output-node-indent
With xmlstarlet :使用xmlstarlet :
$ xmlstarlet ed -u '//@online_hostname' -v 'newhost' input.xml
Storing in the environment variable存放在环境变量中
MYVAR="newhost"
It could be solved like this可以这样解决
sed -rie 's@online_hostname="(.*?) (.*)"@online_hostname="'$MYVAR'" \2@' test.xml
the first group of regular expression matches lazy to " in other words, first appearance of ".第一组正则表达式懒惰地匹配“”,换句话说,“”的第一次出现。 The second group (.*) meaning anything, is preserved in \2, using @ as separator -i as in-place of and r as extended regular expressions.第二组 (.*) 表示任何内容,保留在 \2 中,使用 @ 作为分隔符 -i 作为替代和 r 作为扩展正则表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.