<root>
<tag>1</tag>
<tag1>2</tag1>
</root>
Need to change values 1 and 2 from bash
XML files can also be edited using your computer's notepad program and even with certain word processing and spreadsheet programs. However, XML editors are considered advantageous because they are able to validate your code and ensure you remain within a valid XML structure.
To edit any config file, simply open the Terminal window by pressing the Ctrl+Alt+T key combinations. Navigate to the directory where the file is placed. Then type nano followed by the filename that you want to edit. Replace /path/to/filename with the actual file path of the configuration file that you want to edit.
To change tag
's value to 2
and tag1
's value to 3
, using XMLStarlet:
xmlstarlet ed \
-u '/root/tag' -v 2 \
-u '/root/tag1' -v 3 \
<old.xml >new.xml
Using your sample input:
xmlstarlet ed \
-u '/root/tag' -v 2 \
-u '/root/tag1' -v 3 \
<<<'<root><tag>1</tag><tag1>2</tag1></root>'
...emits as output:
<?xml version="1.0"?>
<root>
<tag>2</tag>
<tag1>3</tag1>
</root>
Since you give a sed
example in one of the comments, I imagine you want a pure bash solution?
while read input; do
for field in tag tag1; do
case $input in
*"<$field>"*"</$field>"* )
pre=${input#*"<$field>"}
suf=${input%"</$field>"*}
# Where are we supposed to be getting the replacement text from?
input="${input%$pre}SOMETHING${input#$suf}"
;;
esac
done
echo "$input"
done
This is completely unintelligent, and obviously only works on well-formed input with the start tag and the end tag on the same line, you can't have multiple instances of the same tag on the same line, the list of tags to substitute is hard-coded, etc.
I cannot imagine a situation where this would be actually useful, and preferable to either a script or a proper XML approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With