linux - 在两个连续行上搜索两个模式并在匹配前打印 n 行

标签 linux bash shell grep

我想使用 shell 命令对匹配两个不同模式的两个连续行进行 grep 或搜索,例如匹配第 1 行:“abc”,第 2 行:“def”。因此,对于以下文本,应该有一个匹配项:第 4 行和第 5 行。

1234
abc-noise
6789
abc-noise
def-noise
def-noise
1234

当我找到这样的匹配时,我想打印它,包括匹配前的 N 行。有任何想法吗?谢谢。

最佳答案

PCRE 模式下使用 GNU grep,启用 -P 标志,

grep -ozP ".*abc.*\n.*def.*" file

对输入文件使用pcregrep

cat file
1234
abc-noise
6789
abc-noise
def-noise
def-noise
1234
noise-abc-noise
noise-noise-def

对于多行模式匹配,做

pcregrep -M  'abc.*\n.*def' file 
abc-noise
def-noise
noise-abc-noise
noise-noise-def

对于模式匹配之前的行,使用 -B 标志,如 GNU grep

pcregrep -B2 -M  'abc.*\n.*def' file 
abc-noise
6789
abc-noise
def-noise
def-noise
1234
noise-abc-noise
noise-noise-def

man pcregrep 页面中关于标志 -M-B 的更多信息,

-M, --multiline Allow patterns to match more than one line. When this option is given, patterns may usefully contain literal newline characters and internal occurrences of ^ and $ characters. The output for a successful match may consist of more than one line, the last of which is the one in which the match ended. If the matched string ends with a newline sequence the output ends at the end of that line.

-B number, --before-context=number Output number lines of context before each matching line. If filenames and/or line numbers are being output, a hyphen separator is used instead of a colon for the context lines. A line containing "--" is output between each group of lines, unless they are in fact contiguous in the input file.

关于linux - 在两个连续行上搜索两个模式并在匹配前打印 n 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41619226/

相关文章:

linux - 如何比较同一文件中的两列,并根据它将差异存储在新文件中与未更改的列中?

bash - 尝试在给定文件的每一行末尾添加一个字符,是如何完成的?

linux - 如何在linux中的eclipse中检索SVN+SSH用户名

PHP mkdir 权限

regex - 如何过滤 Bash 正则表达式(Linux)中除一个之外的所有值?

linux - 是否可以将 tr 与文件中的内容一起使用?

linux - 为什么这个 cron 作业每分钟运行一次?

java 应用程序和 x11 转发

linux - 在 linux 下搜索和替换?

bash - 如何更新 zip 存档中的一个文件