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="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 . 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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.