[英]grep line containing a pattern to line containing other pattern
說輸入是:
">"1aaa
2
3
4
">"5bbb
6
7
">"8ccc
9
">"10ddd
11
12
我想要此輸出(例如匹配模式“ bbb”的示例):
">"5bbb
6
7
我曾嘗試過grep:
grep -A 2 -B 0 "bbb" file.txt > results.txt
這可行。 然而,之間的行數">"5bbb
和">"8ccc
是可變的。 有誰知道如何使用Unix命令行工具實現這一目標?
使用awk
您可以簡單地使用如下標記:
$ awk '/^">"/{f=0}/bbb/{f=1}f' file
">"5bbb
6
7
您也可以像這樣參數化模式:
$ awk '/^">"/{f=0}$0~pat{f=1}f' pat='aaa' file
">"1aaa
2
3
4
說明 :
/^">"/ # Regular expression that matches lines starting ">"
{f=0} # If the regex matched unset the print flag
/bbb/ # Regular expression to match the pattern bbb
{f=1} # If the regex matched set the print flag
f # If the print flag is set then print the line
這樣的事情應該做到:
sed -ne '/bbb/,/^"/ { /bbb/p; /^[^"]/p; }' file.txt
那是:
/bbb/
和/^"/
之間的行范圍 /bbb/
相匹配,則將其打印出來 "
開頭 這可能對您有用(GNU sed):
sed '/^"/h;G;/\n.*bbb/P;d' file
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.