bash 如何在grep中为新行提供模式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12652568/
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-09-09 22:46:09  来源:igfitidea点击:

How to give a pattern for new line in grep?

bashgrepnewline

提问by tuxnani

How to give a pattern for new line in grep? New line at beginning, new line at end. Not the regular expression way. Something like \n.

如何在grep中为新行提供模式?开头换行,结尾换行。不是正则表达式方式。类似\n。

采纳答案by arash kordi

greppatterns are matched against individual lines so there is no way for a pattern to match a newline found in the input.

grep模式与单个行匹配,因此模式无法匹配输入中的换行符。

However you can find empty lines like this:

但是,您可以找到这样的空行:

grep '^$' file
grep '^[[:space:]]*$' file # include white spaces 

回答by nullrevolution

try pcregrepinstead of regular grep:

尝试pcregrep而不是常规grep

pcregrep -M "pattern1.*\n.*pattern2" filename

the -Moption allows it to match across multiple lines, so you can search for newlines as \n.

-M选项允许它匹配多行,因此您可以将换行符搜索为\n.

回答by Manikandan Rajendran

You can use this way...

你可以用这种方式...

grep -P '^\s$' file
  • -Pis used for Perl regular expressions (an extension to POSIX grep).
  • \smatch the white space characters; if followed by *, it matches an empty line also.
  • ^matches the beginning of the line. $matches the end of the line.
  • -P用于 Perl 正则表达式(POSIX 的扩展grep)。
  • \s匹配空白字符;如果后跟*,它也匹配一个空行。
  • ^匹配行的开头。$匹配行尾。

回答by rubystallion

Thanks to @jarno I know about the -z option and I found out that when using GNU grep with the -P option, matching against \nis possible. :)

由于@jarno我知道-z选项,我发现,使用-P选项GNU的grep时,匹配针对\n可能。:)

Example:

例子:

grep -zoP 'foo\n\K.*'<<<$'foo\nbar'

grep -zoP 'foo\n\K.*'<<<$'foo\nbar'

Prints bar

印刷 bar

回答by kenorb

As for the workaround (without using non-portable -P), you can temporary replace a new-line character with the different one and change it back, e.g.:

至于解决方法(不使用 non-portable -P),您可以临时用不同的换行符替换换行符并将其更改回来,例如:

grep -o "_foo_" <(paste -sd_ file) | tr -d '_'

Basically it's looking for exact match _foo_where _means \n(so __= \n\n). You don't have to translate it back by tr '_' '\n', as each pattern would be printed in the new line anyway, so removing _is enough.

基本上它正在寻找精确匹配_foo_,其中的_意思是\n(so __= \n\n)。您不必将其翻译回tr '_' '\n',因为无论如何每个模式都会打印在新行中,因此删除_就足够了。

回答by HHHartmann

just found

刚发现

grep $'\r'

It's using $'\r'for c-style escape in Bash.

$'\r'用于 Bash 中的 c 风格转义。

in this article

这篇文章中