Linux 我在 GNU sed 中的前瞻正则表达式有什么问题?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12176026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's wrong with my lookahead regex in GNU sed?
提问by yegor256
This is what I'm doing (simplified example):
这就是我正在做的(简化示例):
gsed -i -E 's/^(?!foo)(.*)$/bar/' file.txt
I'm trying to put bar
in front of every line that doesn't start with foo
. This is the error:
我试图将bar
每行不以foo
. 这是错误:
gsed: -e expression #1, char 22: Invalid preceding regular expression
What's wrong?
怎么了?
采纳答案by Birei
As far as I know sed
has not neither look-ahead nor look-behind. Switch to a more powerful language with similar syntax, like perl
.
据我所知sed
,既没有向前看也没有向后看。切换到具有相似语法的更强大的语言,例如perl
.
回答by hostmaster
You use perl compatible regular expression (PCRE) syntax which is not supported by GNU sed. You should rewrite your regex according to SED Regular-Expressionsor use perl instead.
您使用 GNU sed 不支持的 perl 兼容正则表达式 (PCRE) 语法。您应该根据 SED正则表达式重写您的正则表达式或改用 perl。
回答by kkeller
sed -i '/^foo/! s/^/bar/' file.txt
-i
change the file in place/^foo/!
only perform the next action on lines not!
starting with foo^foo
s/^/bar/
change the start of the line to bar
-i
更改文件到位/^foo/!
只在不!
以foo开头的行上执行下一步操作^foo
s/^/bar/
将行的开头更改为 bar