正则表达式替换为 sed
我正在 PHP 文件中进行替换,并且需要使用 sed 更改语言变量。这是我的工作代码:
sed -i '' -e "s/\$config\['language'\] = \"english\";/\$config['language'] = '$LANGUAGE';/" Sources/$APP/application/config/config.php
这无法匹配任何语言集:
sed -i '' -e "s/\$config\['language'\] = \"*\";/\$config['language'] = '$LANGUAGE';/" Sources/$APP/application/config/config.php
出了什么问题?
I'm making replacments in PHP file and I need to change the language variable with sed. Here my WORKING code:
sed -i '' -e "s/\$config\['language'\] = \"english\";/\$config['language'] = '$LANGUAGE';/" Sources/$APP/application/config/config.php
This is not working to match any language set:
sed -i '' -e "s/\$config\['language'\] = \"*\";/\$config['language'] = '$LANGUAGE';/" Sources/$APP/application/config/config.php
What's wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在
sed
中,星号 (*
) 字符表示“重复前一操作 0 次或多次”。这与外壳形成鲜明对比,外壳可以扩展到任何东西。你想要做的就是在星号之前添加一个.
(意思是“任何东西”),如下所示:然后这将告诉你的程序“重复任何字符(
.) 任意次数 (
*
)”。In
sed
, the asterisk (*
) character denotes "repeat the previous thing 0 or more times." This is in contrast to a shell, where it expands to anything. What you want to do is shove a.
(which means "anything"), right before the asterisk, like so:That will then tell your program "repeat any character (
.
) any number of times (*
)".那是因为
*
并没有按照您的想法进行操作。在sed
正则表达式中,与所有正则表达式一样,使用.*?
表示任何字符集合(换行符除外)。这是因为.
表示匹配任何内容一次,而*
表示匹配前一项任意多次。?
使其成为非贪婪的,这意味着只要表达式的其余部分匹配,它就会匹配尽可能少的字符。我不知道你输入的是什么,所以我无法判断你是否需要问号,安全总比抱歉好。That's because
*
doesn't do what you think it does. In ased
regular expression, as in all regular expressions, use.*?
to mean any collection of characters (except newlines). That is because.
means match anything once and*
means match the previous item any number of times. The?
makes it non-greedy, meaning it will match as few characters as possible as long as the rest of the expression matches. I don't know what you input is so I can't tell if you need the question mark, better safe than sorry.您需要将表达式中的
*
替换为.*
。*
表示“前一项的 0 个或多个实例”(在本例中为"
),因此您需要首先匹配.
(任何字符),然后声明您想要 0 个或多个 that 实例。You need to replace the
*
in the expression with.*
.*
means "0 or more instances of the previous item" (in this case the"
), so you want to first match.
(any character), then state you want 0 or more instances of that.