CQM
CQM

Reputation: 44278

bash string replacement in a file

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

Upvotes: 1

Views: 298

Answers (2)

Mark Longair
Mark Longair

Reputation: 467581

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:

<?xml version="1.0"?>
<foo>
  <class name="replace_after_this_string">randomtext</class>
  <class name="not_for_replacing">some other text</class>
</foo>

... then this command:

xmlstarlet ed -u './/class[@name="replace_after_this_string"]' \
    -v 'REPLACED HERE' 12477913.xml

... would produce the following output:

<?xml version="1.0"?>
<foo>
  <class name="replace_after_this_string">REPLACED HERE</class>
  <class name="not_for_replacing">some other text</class>
</foo>

Upvotes: 3

Brian Agnew
Brian Agnew

Reputation: 272337

I know it doesn't answer your question directly, but I'd use something XML-aware for modifying XML files. That way you'll avoid issues with entity and character encoding, and maintain well-formedness.

It's worth checking out XMLStarlet as a command-line XML toolkit.

Upvotes: 2

Related Questions