如何在grep中使用多行作为组分隔符?

fed*_*qui 12 shell grep quoting

grep您可以使用--group-separator在组比赛之间写一些东西。

这有助于清楚我们有哪些块,尤其是在使用-C X选项获取上下文行时。

$ cat a
hello
this is me
and this is
something else
hello hello
bye
i am done
$ grep -C1 --group-separator="+++++++++" 'hello' a
hello
this is me
+++++++++
something else
hello hello
bye
Run Code Online (Sandbox Code Playgroud)

我在使用空行作为 grep 的上下文“组分隔符”中学到如何只拥有一个空行,说--group-separator="".

但是,如果我想有两个空行怎么办?我试着说,--group-separator="\n\n"但我得到了字面意思\n

$ grep -C1 --group-separator="\n\n" 'hello' a
hello
this is me
\n\n
something else
hello hello
bye
Run Code Online (Sandbox Code Playgroud)

其他类似的东西--group-separator="\nhello\n"也不起作用。

fed*_*qui 13

哦哦,我找到了,我只需要使用$''语法而不是$""

$ grep -C1 --group-separator=$'\n\n' 'hello' a
hello
this is me



something else
hello hello
bye
Run Code Online (Sandbox Code Playgroud)

来自man bash

引用

$'string' 形式的词被特殊处理。单词扩展为字符串,并按照 ANSI C 标准的规定替换反斜杠转义字符。反斜杠转义序列(如果存在)按如下方式解码:

(...)
\n     new line
Run Code Online (Sandbox Code Playgroud)