簡體   English   中英

在兩個連續行上搜索兩個模式並在匹配前打印 n 行

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM