Reputation: 33
I need to read (store in variable) and then change the online_hostname key value in XML using bash/shell script.
<?xml version="1.0" encoding="UTF-8" ?>
<bzinfo>
<myidentity online_hostname="testdevice-air_2022_01_25"
bzlogin="[email protected]" />
</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/'
Upvotes: 1
Views: 455
Reputation: 3443
Please DO NOT use sed
to parse/edit XML! Use an XML-parser instead.
With xidel:
$ 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 ed -u '//@online_hostname' -v 'newhost' input.xml
Upvotes: 2
Reputation: 2354
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.
Upvotes: 1