Search and Append

All,

I stuck up for the logic, how to implement the below thing in script.

-Search for

<a class="string-array">

line and in next line of search string append with

<string>java</string>

in a xml file

The problem here is,

<a class="string-array">

occurs multiple places in the xml. I just need to append the above mentioned line in first occurrence of

<a class="string-array">

Any hints?????

-Vinodh' Kumar

try with sed..

sed '0,/<a class="string-array">/s//&\n<string>java</string>/' inputfile > outfile

Got the below exception,

sed: -e expression #1, char 49: unknown option to `s'

forward slash need to be escaped..

sed '0,/<a class="string-array">/s//&\n<string>java<\/string>/' inputfile > outfile
1 Like

sed '0,... is GNU sed only... and so is s// ,/ instead of s/$/

Try:

awk -v s="<string>java</string>" '
/<a class="string-array">/ && !f{$0=$0 RS s;f=1}
1' file
awk '1;/<a class="string-array">/&&!p++{print "<string>java</string>"}'
awk -v tag="<a clase=\"string-array\">" '$0~tag {++a["tag"]}{print (($0~tag && a["tag"]==1)?$0"\n<string>java</string>":$0)}' urfile
sed '0,/<a class="string-array">/s//&\n<string>java<\/string>/' inputfile > outfile

This exactly worked for me.

One more hint required,

I set the pattern values into variables and trying to run. But I get below exception, can I know what wrong am doing..

sed '0,/'$searchenv'/s//&\n'$appendenv'/' config.xml > temp.xml

Error: sed '0,/'$searchenv'/s//&\n'$appendenv'/' config.xml > temp.xml

I tried double/single quote to variable in sed.

You would need to use double quotes..

searchenv='<a class="string-array">'
appendenv='<string>java<\/string>'

sed "0,/$searchenv/s//&\n$appendenv/"

No exceptions or No Changes in output file on using latest command mentioned

sed "0,/$searchenv/s//&\n$appendenv/"

can you post your execution line..?

sed "0,/$searchenv/s//&\n$appendenv/" inputfile > outfile
1 Like

Sorry just I made a mistake in setting the value to variable.

The command

 sed "0,/$searchenv/s//&\n$appendenv/" inputfile > outfile

worked perfectly.

Thanks once again.

i guessed that would happen and posted the variable values in post# 10 :cool: :wink: