0

In many PHP files I have defined the variable $_PATHROOT like this

$_PATHROOT = '../../../../';

And I would to replace it with define():

define('_PATHROOT', '../../../../');

Of course, the value ../../../../ differs from one file to another.

Would it be possible with linux sed command line?

Thanks.

0

2 Answers 2

1

It's definitely possible.

The following command should work for any script (it worked for me on a test file):

sed -ri "s/^[$]_PATHROOT = '(([.][.]\/)+)';$/define('_PATHROOT', '\1');/" FILEPATH

where you replace FILEPATH with the path of the file to be edited.

This command assumes that the line you want to change is exactly

$_PATHROOT = '../../';

except that there may be any positive number of "../"s. Any variations in whitespace will throw it off, so if that varies across files you'll need to modify it.

Credit to Kent for the idea of using [$] instead of a mess of backslashes as $ has special meaning in both bash and sed.

Sign up to request clarification or add additional context in comments.

Comments

0

This sed one-liner works for the given example:

sed -r "s/^[$](\w+)(.*);/define('\1'\2);/;s/=/,/"

:

kent$  sed -r "s/^[$](\w+)(.*);/define('\1'\2);/;s/=/,/"<<<"\$_PATHROOT = '../../../../';"  
define('_PATHROOT' , '../../../../');

4 Comments

Yes but the value may change, it can be for example '../../' and I would like to execute the sed command in a find command find -type f -name "*.php" -exec sed -i .... Is it possible?
I imagine the PHP files will contain other lines as well. Wouldn't this pattern likely affect other unrelated lines, given how many lines in PHP start with $?
It depends on the file, they don't have the same number of lines starting with $.
I didn't hard code the value part, so it should work on other values too. @LondonSmith

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.