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/'
Thanks
CodePudding user response:
It could be solved like this
sed -i 's@online_hostname=".*"@online_hostname="'"$MYVAR"'"@' test.xml
storing in
MYVAR="newhost"
using @ as separator -i as in-place of
CodePudding user response:
Here's an example with xmlstarlet
:
- Get the attribute value:
xmlstarlet sel -t -v '/bzinfo/myidentity/@online_hostname' test.xml
testdevice-air_2022_01_25
- Update the attribute value:
xmlstarlet ed -u '/bzinfo/myidentity/@online_hostname' -v 'air&wired' test.xml
<?xml version="1.0" encoding="UTF-8"?>
<bzinfo>
<myidentity online_hostname="air&wired" bzlogin="[email protected]"/>
</bzinfo>
note: you can use the global option -L
for inplace editing xmlstarlet ed -L -u ...