gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:56:04 26 4
gpt4 key购买 nike

我想使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com