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="[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/'
1

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

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.
Also <myidentity online_hostname="michael-g’s-macbook-air_2022_04_18" bzlogin="[email protected]" /> is a one liner. This command removes the bzlogin="[email protected] part. Thanks.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.