1

I'm looking to run script or command to mass change a string that is a URL. I've viewed many examples on this forum, however none are working.

I have created a .sh file to run the following:

$SRC='$url = "https://www.myurl.com/subdir/process.do"';
$DST='$url="https://api.myurl.com/subdir/process.do"';
find . -type f -name "*.php" -exec sed -i 's/$SRC/$DST/g' {} +;

This is not working. I'm thinking it may because of having backslashes in the search content? The search/replace is needed to be run across all sub-directories on .php files.

Any assistance would be greatly appreciated.

Thanks!

Jonathon
  • 778
  • 8
  • 21
  • 1
    Possible duplicate of [How to use SED to find and replace URL strings with the "/" character in the targeted strings?](https://stackoverflow.com/q/16778667/608639) and [Use slashes in sed replace](https://stackoverflow.com/q/5864146/608639). – jww Mar 27 '18 at 18:02

1 Answers1

1

First thing - check your variable definitions. In bash, variable definitions usually do not start with a leading $. Ie, should be:

SRC='$url = "https://www.myurl.com/subdir/process.do"';
DST='$url="https://api.myurl.com/subdir/process.do"';

Next, you should switch to using single quotes for the pattern, and double quotes for the variable, as per: https://askubuntu.com/questions/76808/how-do-i-use-variables-in-a-sed-command

Example that seems to work:

sed -i 's,'"$SRC"','"$DST"','

UPDATE: This exact script works perfectly for me on Linux:

 #!/bin/bash
 SRC='$url = "https://www.myurl.com/subdir/process.do"'; 
 DST='$url="https://api.myurl.com/subdir/process.do"';
 find . -type f -name "*.php" -exec sed -i 's,'"$SRC"','"$DST"',' {} \;

Contents of file "asdf.php" created in home directory (before running script):

 $url = "https://www.myurl.com/subdir/process.do"

Contents of file "asdf.php" after running script:

 $url="https://api.myurl.com/subdir/process.do"
Richard Zack
  • 431
  • 3
  • 12
  • Your solution did not seem to work. I also tried with removing the variables all together. find . -type f -name *.php -exec sed -i 's/'"https://www.myurl.com/subdir/process.do"'/'"https://api.myurl.com/subdir/process.do"'/g' {} +; – user1594099 Mar 28 '18 at 12:53
  • Try with commas and not slashes, ie: find . -type f -name *.php -exec sed -i 's,'"yoururl"','"yournewurl"',' {} \; – Richard Zack Mar 28 '18 at 13:20
  • That seems to help, but there are other errors happening. String found where operator expected at search.sh line 1, near "name '*.php'" (Do you need to predeclare name?) String found where operator expected at name.sh line 1, near "i 's,"https://www.myurl.com/subdir/process.do","https://api.myurl.com/subdir/process.do",g'" (Do you need to predeclare i?) syntax error at search.sh line 1, near "name '*.php'" – user1594099 Mar 28 '18 at 13:45