grep行包含一个包含其他模式的行的模式

时间:2013-12-29 23:45:08

标签: regex unix sed awk grep

说输入是:

">"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命令行工具实现这一目标?

3 个答案:

答案 0 :(得分:3)

使用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

答案 1 :(得分:2)

这样的事情应该这样做:

sed -ne '/bbb/,/^"/ { /bbb/p; /^[^"]/p; }' file.txt

那是:

  • 表示匹配/bbb//^"/
  • 之间的行数范围
  • 如果该行匹配/bbb/则将其打印
  • 如果该行不以"打印
  • 开头
  • 否则没有其他内容打印

答案 2 :(得分:0)

这可能适合你(GNU sed):

sed '/^"/h;G;/\n.*bbb/P;d' file
相关问题