Problem with awk while handling special charaters

Hi,

I have an application.xml file like
</dependency>
<artifactId>_AdminServicesEAR</artifactId>
<version>1.0.0-20080521.085352-1</version>
<context-root>oldvalue</context-root>
<type>ear</type>
<DOCTYPE "abc/xyz/eft">
<NewTag>value123</xyz>
<NewTag>value321</abcd>
</dependency>

i need to search & replace the value inside <NewTag> based on the input parameter which iam passing to the script.

eg : ./sampleawk 1 will replace the first occurance of <NewTag>
The command which i am using is

awk -v n=$OCCURENCE -v s="<$KEY>$VALUE<\/" "/<$KEY>(.+)<\//&&n==++c{sub(\"<$KEY>(.+)<\/\",s)}1"

But this command is not working properly if the "$VALUE" contains some
special characters like & , % etc...

CAn anyone help me to change the exisiting command for handling special charcters ???

Thanks in advance

You are already escaping the slash; escaping the values in $VALUE before passing it in would seem like the simplest change. Maybe write a wrapper script for passing in OCCURRENCE (correctly spelled :^), KEY, and VALUE properly escaped would be the way to go.

$n=shift;
$new=shift;
open (FH,"<file");
while(<FH>){
	if(m/<NewTag>/){
		$t++;
	}
	if($t==$n){
		s/<NewTag>/<$new>/;
	}
	print;
}
perl sample.pl 1 perl

You could use sed like this to insert appropriate escapes:

OCCURRENCE=2
VALUE='test&test$test'
NEWVALUE=$(echo "$VALUE" | sed 's/&/\\\\&/g;s/[$]/\\\$/g')
KEY=NewTag
awk -v n=$OCCURRENCE -v s="<$KEY>$NEWVALUE<\/" "/<$KEY>(.+)<\//&&n==++c{sub(\"<$KEY>(.+)<\/\",s)}1" 

ETA: cross-posted, looks like I simply implemented era's suggestion.

Thanks a lot all ...

Its working fine for me........