簡體   English   中英

grep包含模式的行到包含其他模式的行

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

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