views:

26

answers:

1

Hello,

Lets say I want to replace the following string within a textfile:

document.write(unescape("%3Cscript src='" + \ + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

I came up with this sed command, but surprisingly nothing happens at all.

sed -i "s/document.write(unescape(\"%3Cscript src=\"\' + \\ + \"google-analytics.com\/ga.js\' type=\'text\/javascript\'%3E%3C\/script%3E\"));//g" myfile.html

Whats wrong here?

+1  A: 

There are several issues here:

  1. backslashes should be doubly escaped, since they are expanded by both sed and the shell, so \\\\ (becomes \\ in the shell, then \ in sed)
  2. you're matching on src="', but your file contains src='"

Here's a correct command; I've also replaced / with | to make it more readable (no more need to escape /) and removed the superfluous escaping of '.

sed -i \
"s|document.write(unescape(\"%3Cscript src='\" + \\\\ + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));||g" \
myfile.html
larsmans
Thanks, I didn't know the trick with the pipe. However, shouldn't this one work, too? "s/document.write(unescape(\"%3Cscript src='\" + \\\\ + \"google-analytics.com\/ga.js' type='text\/javascript'%3E%3C\/script%3E\"));//g"
Should work, but I decided on pipes before further editing your command. It doesn't only work with `|` by the way, other characters are possible (see the `sed` manual).
larsmans