使用 sed 替换变量名及其值 [英] Using sed to replace variable name and its value

查看:63
本文介绍了使用 sed 替换变量名及其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多 PHP 文件中,我已经像这样定义了变量 $_PATHROOT

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

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

我想用 define() 替换它:

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

当然,../../../../的值因文件而异.

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

linux sed 命令行可以吗?

Would it be possible with linux sed command line?

谢谢.

推荐答案

绝对有可能.

以下命令适用于任何脚本(它适用于我的测试文件):

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.

感谢 Kent 使用 [$] 而不是一堆反斜杠的想法,因为 $ 在 bash 和 sed 中都有特殊含义.

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

这篇关于使用 sed 替换变量名及其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆