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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:12:21  来源:igfitidea点击:

What's wrong with my lookahead regex in GNU sed?

regexlinuxsedregex-lookarounds

提问by yegor256

This is what I'm doing (simplified example):

这就是我正在做的(简化示例):

gsed -i -E 's/^(?!foo)(.*)$/bar/' file.txt

I'm trying to put barin 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 sedhas 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
  • -ichange 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