![](/img/trans.png)
[英]How can I search for two different patterns in two consecutive lines in a file using SED and print next 4 lines after pattern match?
[英]Search two patterns on two consecutive lines and print n lines before the match
我想使用 shell 命令对匹配两种不同模式的两个连续行进行 grep 或搜索,例如匹配 line1:“abc”,用于 line2:“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
对于模式匹配之前的行,请使用GNU grep
的-B
标志
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 允许模式匹配多于一行。 当给出这个选项时,模式可能有用地包含文字换行符和 ^ 和 $ 字符的内部出现。 成功匹配的输出可能包含多行,最后一行是匹配结束的那一行。 如果匹配的字符串以换行序列结尾,则输出在该行的末尾结束。
-B number, --before-context=number 在每个匹配行之前输出上下文的行数。 如果正在输出文件名和/或行号,则使用连字符分隔符代替上下文行的冒号。 在每组行之间输出包含“--”的行,除非它们实际上在输入文件中是连续的。
扩展@Inian 的好答案,如果你想在整个目录中递归搜索:
find my_code_dir/ -type f -name "*.py" -exec pcregrep -B2 -M 'except.*\n.*pass' {} +
这个特定的命令将查找包含except
出现行,紧接着是包含pass
的行,但仅在.py
文件中。
#!/bin/bash
a=''
b=''
while read c; do
a=$b;
b=$c;
if [ `echo "$a" |grep "abc"` ] & [ `echo "$b" |grep "def"` ]; then
echo $a;
echo $b;
break;
fi
done
发射:
$./find2pat
wegweg
egwergwerg
sdfabcerg
rrheedef4
输出:
sdfabcerg
rrheedef4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.