当对上下文行使用 grep 时,如何去除“——”行分隔符?

我有一个名为 compare.txt的文本文件,其中我想提取包含模式 nmse_gain_constant的每一行后面的一行。下面的命令让我靠近:

grep -A 1 nmse_gain_constant compare.txt | grep -v nmse_gain_constant

但是,这包括一个分隔符 --行之间的每一行所需的文本。有什么简单的办法可以去掉 --线吗?

示例: 输入文件类似于

line
line
nmse_gain_constant matching line
line after first match
line
line
nmse_gain_constant another matching line
line after second match
line
nmse_gain_constant a third matching line
line after third match

输出是

line after first match
--
line after second match
--
line after third match

但我希望

line after first match
line after second match
line after third match
42230 次浏览

一个解决办法是:

grep -A 1 nmse_gain_constant compare.txt | grep -v nmse_gain_constant  | grep -v "\-\-"

默认情况下,A开关会添加这些字符,所以这并不神秘。

man grep指出:

-A NUM


Places  a  line  containing  a  group  separator  (--)   between
contiguous  groups  of  matches.  With the -o or --only-matching
option, this has no effect and a warning is given.

但是您可以使用一个简单的 sed 来清理结果:

yourgrep | sed '/^--$/d'

如果您使用 AWK,就不需要管道到这么多 grep 或使用其他工具(例如 sed) :

awk '/nmse_gain_constant/{getline;print }' compare.txt

Grep 有一个没有文档说明的参数: “—— group-analysis ator”,它覆盖了默认的“——”。你可以把它设置为“”来去掉双破折号。尽管如此,你还是得到了一个空行。我遇到了同样的麻烦,通过读取 grep 的源代码找到了这个参数。

我这样做:

 grep ... | grep -v -- "^--$"

但是这也可以工作(对于很多操作系统,并不是所有的操作系统) !

grep --no-group-separator ...

而且它没有吐出那个“——”甚至没有一行空白。