Add string after another string with special characters

Hello everyone,

I'm writing a script to add a string to an XML file, right after a specified string that only occurs once in the file. For testing purposes I created a file 'testfile' that looks like this:

1
2
3
4
5
6
6
7
8
9

And this is the script as far as I've managed:

XMLSTRING="<thema xmlns=\"x-schema:df.ase\" uid=\"asd_F\" displayname=\"Jdddf 1\" asd_jg_id=\"6\" asd_jg_id_an=\"F\"/>"

awk '{ if ( $0 ~ /4/ ) {
        printf( "%s\n%s\n", $0, "'"$XMLSTRING"'" );
     }else{
        print $0;
     }
}' testfile

In this case, what I want it to to is to find '4' (will be a string in an XML file later) and to insert the value of $XMLSTRING on the line underneath. This all works fine when $XMLSTRING has a value without any strange characters, but in this case I get an error:

awk: cmd. line:2: 	 	printf( "%s\n%s\n", $0, "<thema xmlns=\"x-schema:df.ase\" uid=\"asd_F\" displayname=\"Jdddf 1\" asd_jg_id=\"6\" asd_jg_id_an=\"F\"/>" );
awk: cmd. line:2: 	 	                                                ^ syntax error

In case the formatting mangles this, the syntax error points to the first ':' in the inserted string.

My question is; in what way can I handle this so that it does print the string correctly? What I'm looking for in this case, is this:

1
2
3
4
<thema xmlns="x-schema:df.ase" uid="asd_F" displayname="Jdddf 1" asd_jg_id="6" asd_jg_id_an="F"/>
5
6
7
7
8
9

Any help would be greatly appreciated!

Place the xml string within single quotes and use an awk variable.
This should work:

#!/bin/sh

XMLSTRING='<thema xmlns=\"x-schema:df.ase\" uid=\"asd_F\" displayname=\"Jdddf 1\" asd_jg_id=\"6\" asd_jg_id_an=\"F\"/>'

awk -v var="$XMLSTRING" '
  {if ( $0 ~ /4/ ) {
    printf( "%s\n%s\n", $0, var )
  }
  else {
    print $0
  }
}' testfile

Regards

Wow, that worked, thanks! I didn't know you could pass variables to awk like that, this is great!

Thanks again!