You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

批量替换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 sed command in single quotes ('s/$SRC/$DST/g'). Bash doesn't expand variables inside single quotes, so sed was literally trying to match the string $SRC instead of your actual URL. We need double quotes here to let Bash replace the variables with their values.
  • Slash Conflicts: sed uses / as the default delimiter for substitution. Since your URLs contain / characters, sed gets confused—it thinks the first / after s is 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 the sed substitution—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 SRC and DST ensure 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

火山引擎 最新活动