Karthikeyan M
Karthikeyan M

Reputation: 33

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.

<?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

Answers (2)

Reino
Reino

Reputation: 3443

Please DO NOT use sed to parse/edit XML! Use an XML-parser instead.

With :

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

With :

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

Upvotes: 2

Pepe N O
Pepe N O

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

Related Questions