Had to insert a XML-snippet into another XML-file at a given location in a Bash-script. Reading the snippet into a variable is quite easy, just by using cat. The trouble was how to find the tag to replace most efficiently, then replace it with the xml-snippet. Learned that reading the file content using stdin/stdout in a bash-script can cause side effects not easy to figure out, so that was no option. Instead I first tried to use sed, but sed had problems with the fact that the content of the snippet is XML-code. So instead with good help from Geir we ended up using Perl, which made it all very simple – everything done in just 2 lines of code.

First it searches for <!– END jaas –> then replaces the string with the content of the snippet variable and lt;!– END jaas –>

value=$(cat jaas_snippet.xml)
perl -pi -e "s#<!--\sEND\sjaas\s-->#${value}\n\t\t<!-- END jaas -->#" jaas.xml

Comments:

  • Using # instead of ` – while struggling with XML in the variable $value
  • \s = whitespace, like \n is newline and \t is tab
  • Double quote’s so that perl uses the value of the variable, and not just reads it as plain text
  • In this case we expect only one occurrence of the end-tag, so we have skipped the /g parameter at the end of the search-string. /g meaning global, compared to for instance the usage described in my previous blog post at WPC.

Perl is power!