0

I have php files with the flag like /* TEST */.

In the script, I have variables with this flag and the value to replace:

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

My code returns no errors, but flags aren't replaced:

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

2 Answers 2

2

Your sed string is in single quotes. Variable expansion does not occur there. Switch to double quotes:

find . -name "*.php" -exec sed -i -e "s/$testPattern/$test/g" {} \;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer. In this case I get errors: sed: 1: "s//* TEST *//defined('_J ...": bad flag in substitute command: '/'
You have to adjust the pattern to be properly escaped, otherwise, sed is interpreting it according its rules. In particular, you should escape the characters with special meaning for sed, the slash and the start of $testPattern.
0

Enclosing characters in single quotes preserves the literal value of each character within the quotes.

Try this one:

sed -i '' "s~$testPattern~$test~g" $(find . -name '*.php')

3 Comments

Thanks for the answer. Unfortunately it also doesn't replace.
Can you check the latest edit? on MacOS the -i flag requires a specified extension following the flag, in this case ''. (If a zero-length extension is given, no backup will be saved)
Yes. I've checked this the last edit. The same result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.