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
How to give a pattern for new line in grep?
提问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
grep
patterns 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 pcregrep
instead of regular grep
:
尝试pcregrep
而不是常规grep
:
pcregrep -M "pattern1.*\n.*pattern2" filename
the -M
option 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
-P
is used for Perl regular expressions (an extension to POSIXgrep
).\s
match 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 \n
is 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