I am trying to replace some text in a file replacetest.xml
here is the part of the file I want to modify.
<class name="replace_after_this_string">randomtext</class>
I want to change the text randomtext with the text at the index of my array
orgs=( item1 item2 )
and overwrite the file with these modifications.
My main issues are with wildcards and the sed command. So here is what I tried
orgs=( item1 item2 )
SRC="name="'"replace_after_this_string"'">"
#need some sort of wildcard here
for i in "${orgs[@]}"
do
:
# do whatever on $i
DST=$SRC$i
sed -e 's/$SRC/$DST/g' -i replacetest.xml
done
1) I need a wildcard to designate that I want to replace randomtext after identifying what will be in the variable $SRC
2) My sed statement doesn’t do anything except print to command line verbatim, does not modify my file at all, even in what is printed to command line
I think sed is the wrong tool for this, since it doesn’t understand the structure of XML files, and as a result, your script will end up being rather brittle even if you can get it to work at all. As Brian Agnew suggests in his answer, xmlstarlet is a helpful tool for manipulating XML files. For example, if your file (
12477913.xml, say) is as follows:… then this command:
… would produce the following output: