正则表达式替换为 sed

发布于 2024-12-22 08:17:40 字数 404 浏览 1 评论 0原文

我正在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

橘味果▽酱 2024-12-29 08:17:40

sed 中,星号 (*) 字符表示“重复前一操作 0 次或多次”。这与外壳形成鲜明对比,外壳可以扩展到任何东西。你想要做的就是在星号之前添加一个.(意思是“任何东西”),如下所示:

sed -i '' -e "s/\$config\['language'\]  = \".*\";/\$config['language'] = '$LANGUAGE';/" Sources/$APP/application/config/config.php

然后这将告诉你的程序“重复任何字符(.) 任意次数 (*)”。

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:

sed -i '' -e "s/\$config\['language'\]  = \".*\";/\$config['language'] = '$LANGUAGE';/" Sources/$APP/application/config/config.php

That will then tell your program "repeat any character (.) any number of times (*)".

煞人兵器 2024-12-29 08:17:40

那是因为 * 并没有按照您的想法进行操作。在 sed 正则表达式中,与所有正则表达式一样,使用 .*? 表示任何字符集合(换行符除外)。这是因为 . 表示匹配任何内容一次,而 * 表示匹配前一项任意多次。 ? 使其成为非贪婪的,这意味着只要表达式的其余部分匹配,它就会匹配尽可能少的字符。我不知道你输入的是什么,所以我无法判断你是否需要问号,安全总比抱歉好。

That's because * doesn't do what you think it does. In a sed 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.

梦里°也失望 2024-12-29 08:17:40

您需要将表达式中的*替换为.** 表示“前一项的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文