我正在使用以下命令来匹配文件中的以下行:
cat file.txt | grep -A 1 'match' > output.txt
这允许我在以下文件中找到“匹配”后获取行:
match
random text line 1
match
match
match
random text line 2
match
random text line 3
match
match
random text line 4
match
random text line 5
match
random text line 6
match
random text line 7
match
random text line 8
match
match
random text line 9
但是,我只需要返回 2 个或多个连续“匹配”行之后的行。在这种情况下,输出将是:
random text line 2
random text line 4
random text line 9
我试过使用 grep -A 2 'match' | 的组合grep -A 1 'match'
但它不起作用,因为它是多余的。我坚持只有在有两条连续线的情况下才能匹配。如果效率更高,我也愿意使用 awk 或 sed 进行匹配。任何方向将不胜感激。
最佳答案
grep 代表 g/re/p
即它用于全局查找正则表达式并打印结果,仅此而已。这不是您尝试这样做的全部,因此 grep 将是尝试使用的错误工具。对于通用文本操作,使用的标准工具是 awk:
$ awk '/match/{c++;next} c>1; {c=0}' file
random text line 2
random text line 4
random text line 9
关于linux - Grep Next Line Only If Two Lines above Match String 连续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39600858/