1

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/'
John Kugelman
  • 349,597
  • 67
  • 533
  • 578

2 Answers2

1

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
Reino
  • 3,203
  • 1
  • 13
  • 21
0

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.

Pepe N O
  • 1,678
  • 1
  • 7
  • 11
  • I am getting the below error when trying sed. "sed: 1: "test.xml": undefined label 'est.xml' ". Also I need the value of online_hostname in a variable. Thanks. – Karthikeyan M Apr 19 '22 at 10:53
  • Also is a one liner. This command removes the bzlogin="it@socure.com part. Thanks. – Karthikeyan M Apr 19 '22 at 15:20
  • sed: 1: "s@online_hostname="(.*? ...": RE error: repetition-operator operand invalid - I tried the new command, got this error. I am on trying on macOS. Is that specific I am missing? Thanks – Karthikeyan M Apr 20 '22 at 05:54