sed has zeored my files. Help me with sed please

i made a script to update a lot of xml files. to save me some time. Ran it and it replaced all the the files with a 0kb file. The problem i was having is that I am using sed to change xml node <doc_root>. The problem with this is it has a / in the closing xml tag and the stuff inside will also have a bunch of / because it is a file path. so i am using sed and was hoping this would work:

sed 's/<doc_root><\/doc_root>/<doc_root>\/'$i'\/web<\/doc_root>/g' $my_file > $my_file

Is my problem in the regex or is it because I am using $my_file > $my_file ? do i need to copy it to a temp file first the mv it to old file?
Or if its the regex can someone help with that
Here is the search string

<doc_root></doc_root>

Here is a typical replace string

<doc_root>/domain.co.uk/web</doc_root>

where the daomin.co.uk will be an argument from a for loop i.e $i

Please help before my boss gets angry with me :frowning:

I will look into the function of the sed but you are redirecting the output to the same file name, you shud never do that. that is why u have 0kb file.

redirect it to a temp file
verify the result
mv tempfile filename

cheers,
Devaraj Takhellambam

sed "s#<doc_root></doc_root>#<doc_root>/$i/web</doc_root>#g" $my_file > /tmp/myTemp && mv /tmp/myTemp $my_file

OR

{ rm $my_file; sed "s#<doc_root></doc_root>#<doc_root>/$i/web</doc_root>#g" > $my_file; } < $my_file

Thanks alot guys that works :slight_smile:

cool lots of variations. This also works

sed 's/<doc_root><\/doc_root>/<doc_root>\/'$i'\/web<\/doc_root>/g' $my_file > "tmp/"$i".xml"
mv "tmp/"$i".xml" $my_file

no need for so many quotes.
Also you need to double quote "$i" in case a file name has embedded quotes:

sed 's/<doc_root><\/doc_root>/<doc_root>\/'"$i"'\/web<\/doc_root>/g' $my_file > "tmp/$i.xml"
mv "tmp/$i.xml" "$my_file"