sed 正则表达式中的全局和分组问题

发布于 2024-07-18 00:48:07 字数 498 浏览 5 评论 0原文

我运行以下 代码

sed 's/\([^ ]+\) your \([^ ]+\)/ \2\1er/' < fail

文件失败

fail your test

是上面的命令给了我,

fail your test

尽管它应该给出“testfailer”。

第二个和第一个 glob \2\1 应该位于单词“er”的开头。 这表明问题可能出在搜索部分的正则表达式中。 然而,它们对我来说似乎是正确的。

您发现代码中有任何错误吗?

I run the following code

sed 's/\([^ ]+\) your \([^ ]+\)/ \2\1er/' < fail

The file fail is

fail your test

The above command gives me

fail your test

although it should give "testfailer".

The second and first globs \2\1 should be at the start of the word "er".
This suggests me that the problem may be in the regexes in the search part.
However, they seem to be correct for me.

Do you see any mistake in the code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

多像笑话 2024-07-25 00:48:07

常见或普通的 sed 正则表达式不理解 +。 是的,我知道,那是多么愚蠢。 因此,这是命令行的等效工作版本:

sed 's/\([^ ][^ ]*\) your \([^ ][^ ]*\)/ \2\1er/' < fail

也可以请求扩展正则表达式,在这种情况下,您可以放弃括号上的反斜杠:

sed -r 's/([^ ]+) your ([^ ]+)/ \2\1er/' < fail

Common or garden variety sed regex doesn't understand +. Yeah, I know, how stupid is that. So this is an equivalent, working version of your command line:

sed 's/\([^ ][^ ]*\) your \([^ ][^ ]*\)/ \2\1er/' < fail

Also works to request extended regex, in which case you ditch the backslashes on the parens:

sed -r 's/([^ ]+) your ([^ ]+)/ \2\1er/' < fail
愛放△進行李 2024-07-25 00:48:07

当您转义加号时,您的代码确实可以工作:

sed 's/\([^ ]\+\) your \([^ ]\+\)/\2\1er/' < fail

Your code does work when you escape the plus signs:

sed 's/\([^ ]\+\) your \([^ ]\+\)/\2\1er/' < fail
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文