使用Bash/Shell脚本读取和修改XML中的键值



我需要读取(存储在变量中),然后使用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>

我可以读取值,但不能改变它。

cat test.xml | grep '<myidentity ' | sed -E 's/.*online_hostname="?([^ "]*)"? .*/1/'

请不要使用sed解析/编辑XML!请使用xml解析器。

与xidel:

$ xidel -s input.xml -e '
x:replace-nodes(//@online_hostname,function($x){attribute {name($x)} {"newhost"}})
' --output-format=xml --output-node-indent

xmlstarlet:

$ xmlstarlet ed -u '//@online_hostname' -v 'newhost' input.xml

存储在环境变量

MYVAR="newhost"

可以这样求解

sed -rie 's@online_hostname="(.*?) (.*)"@online_hostname="'$MYVAR'" 2@' test.xml

第一组正则表达式匹配到"换句话说,第一次出现的"第二组(.*)表示任何东西,保存在2中,使用@作为分隔符-i代替,r作为扩展正则表达式

最新更新