批量替换PHP文件中URL的Shell脚本执行异常求助
Fixing Your Batch URL Replacement Script
Yep, I see exactly where your script is tripping up—those slashes in the URL are clashing with sed's default delimiter, plus there are quoting issues preventing your variables from being expanded correctly. Let's break this down and fix it step by step:
Key Issues in Your Original Script
- Variable Quoting Problem: You wrapped the
sedcommand in single quotes ('s/$SRC/$DST/g'). Bash doesn't expand variables inside single quotes, sosedwas literally trying to match the string$SRCinstead of your actual URL. We need double quotes here to let Bash replace the variables with their values. - Slash Conflicts:
seduses/as the default delimiter for substitution. Since your URLs contain/characters,sedgets confused—it thinks the first/aftersis the end of the search pattern, leading to syntax errors. The fix is to use an alternative delimiter that doesn't appear in your URLs.
Corrected Script
Here's the revised version that should work as expected:
#!/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#g" {} +
Important Notes
- I used
#as the delimiter for thesedsubstitution—since your URLs don't include#, this avoids conflicts entirely. If your URLs ever contained#, you could switch to another unused character like|. - The single quotes around
SRCandDSTensure Bash treats the entire string (including spaces and double quotes) as a single, unbroken value. - Always test first! Before running with
-i(which edits files in-place), verify the replacement works by running this test command (it prints only the lines that would be modified):find . -type f -name "*.php" -exec sed -n "s#$SRC#$DST#gp" {} +
内容的提问来源于stack exchange,提问作者user1594099




