You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Bash按变量值替换PHP文件内容的问题排查

Fixing Sed Replacement for /* TEST */ in PHP Files

Let's break down why your current command isn't working and walk through the correct solutions step by step:

What's Wrong With the Original Command?

Your command wraps the sed script in single quotes, which tells the shell to treat everything inside as a literal string. That means $testPattern and $test never get expanded to their actual values—sed is literally trying to match the string "$testPattern" instead of your /* TEST */ marker. On top of that, the * and / in your marker are special characters in sed's regular expressions, so even if the variables did expand, sed would misinterpret them as regex syntax instead of literal text.

Solution 1: Use GNU Sed's Literal Matching (Simplest)

If you're using GNU sed (standard on most Linux systems), you can use \Q and \E to wrap your pattern. This tells sed to treat everything between them as a literal string, so you don't need to escape special characters like * or /.

First, confirm your variables are defined correctly (no syntax issues here):

test="defined('_TEST') or die('Test test');"
testPattern="/* TEST */"

Then run this command to replace the markers in place:

find . -name "*.php" -exec sed -i -e "s/\Q$testPattern\E/$test/g" {} \;

How This Works:

  • Double quotes around the sed script let the shell expand $testPattern and $test to their actual values before passing them to sed.
  • \Q turns on literal matching mode, \E turns it off—so sed will look for the exact string /* TEST */ instead of trying to parse it as a regex.

Solution 2: Manual Escaping (For BSD Sed, e.g., macOS)

If you're using macOS's default BSD sed, it doesn't support the \Q/\E syntax. Instead, you need to escape the special characters in your pattern first:

  1. Escape / and * in your test pattern to make them literal for sed:
escapedPattern=$(printf '%s' "$testPattern" | sed 's/[\/\*]/\\&/g')

This converts /* TEST */ to \/\* TEST \*\/, which sed will recognize as the exact string you want to match.

  1. Run the find/sed command (note the empty string after -i—BSD sed requires this to skip creating backup files):
find . -name "*.php" -exec sed -i '' -e "s/$escapedPattern/$test/g" {} \;

Verify Before Modifying Files

Before using -i to edit files in place, you can test the command by removing -i (and the empty string for BSD sed) to print the modified content to your terminal:

# GNU sed test
find . -name "*.php" -exec sed -e "s/\Q$testPattern\E/$test/g" {} \;

# BSD sed test
find . -name "*.php" -exec sed -e "s/$escapedPattern/$test/g" {} \;

This lets you confirm the replacement works correctly before making permanent changes to your PHP files.


内容的提问来源于stack exchange,提问作者Irina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:11:32