0

I want to search for a string and replace it with another string recursively under a directory. for example: I want to search for a string

"var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");"

and replace it with

var _gaq = _gaq || [];_gaq.push(['_setAccount', 'UA-7044592-1']);_gaq.push(['_setDomainName', 'news4u.com']);_gaq.push(['_trackPageview']);

How to achieve it ?

JB.
  • 40,344
  • 12
  • 79
  • 106

1 Answers1

0

Use find to find all files, and xargs to run sed to modify them:

find dir -type f | xargs sed -i.bak 's#from#to#'

that will find all files under dir and replace from with to, backing up the original files with the extension ".bak"

N.B. from is a basic regular expression, so you will need to escape any BRE metacharacters in the string you are searching for. It would be a good idea to test the sed command on a single file to get it working:

sed 's#from#to#' file > test.out

That will do the replacements to file but instead of modifying file it will write the output to test.out so you can check the results.

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
  • I tried this below piece of code ( I am replacing with 'goo' just for testing) `find /home/project/new4u/apps/frontend/modules/alerts/templates/testing -type f -exec sed -i "s/var gaJsHost = ((\"https:\" == document.location.protocol) \? \"https:\/\/ssl.\" : \"http:\/\/www.\")/goo/" {} \;` It is not workign properly. I have escaped all the delimiters and still it does not work. Please let me know what changes are to be done. – Manu-dra-kru Jul 09 '12 at 09:19
  • You've escaped too much, `?` is not a BRE metacharacter. Also, if you quote using `'` then you don't need to escape the `"` characters, and if you use `s#from#to#` instead of `s/from/to/` then you don't need to escape the `/` characters. – Jonathan Wakely Jul 09 '12 at 09:48
  • Thanks a lot. I stopped escaping ? and " and it worked. – Manu-dra-kru Jul 09 '12 at 11:19
  • can you please help ne for this [link](http://stackoverflow.com/questions/11411556/how-to-replace-the-following-text-using-sed) – Manu-dra-kru Jul 10 '12 at 10:39