grep匹配模式的行,以及匹配之前和之后直到不同模式的行 [英] grep lines matching a pattern, and the lines before and after the matching until different pattern

查看:119
本文介绍了grep匹配模式的行,以及匹配之前和之后直到不同模式的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Start_pattern
abc
d End_pattern
Start_pattern
abc
d
ef
ghij 
klm
no End_pattern
Start_pattern
abc
def
hij End_pattern
Start_pattern
abc
dhi
jklm End_pattern

所需的输出:

要打印Start_pattern之间的行,包括Search_pattern End_pattern包括开始和结束模式.

To print lines between Start_pattern including Search_pattern End_pattern Start and End pattern inclusive.

Start_pattern
abc
d
ef
ghij 
klm
no End_pattern
Start_pattern
abc
def
hij End_pattern

在上面的文件中,我要搜索"ef"并在"Strat_pattern""End_pattern"之间打印行.

In above file i want to search for "ef" and print lines between "Strat_pattern" and "End_pattern".

  1. 尝试过grep -B[NUM] and -A[NUM],因为可能会没有用 搜索模式"gef"和"Start_pattern"之间的行数未知 和"End_pattern".
  2. grepsedawk任何欢迎的内容.最好是一支班轮.
  3. sed -n '/BEGIN/,/END/p' *用于在Search_patternEnd_pattern之间打印行.但是我无法在Start_pattern"def"
  4. 之间打印行
  5. 存在多个文件,并出现了多次search_pattern
  1. have tried grep -B[NUM] and -A[NUM] which are not useful as there could be unknown number of lines between search pattern "gef" and "Start_pattern" and "End_pattern".
  2. grep, sed , awk anything welcomed. preferentially one liner.
  3. sed -n '/BEGIN/,/END/p' * works to print lines between Search_pattern which is "def" and End_pattern. but iam not able to print lines between Start_pattern and "def"
  4. Multiple files present with multiple occurrences of search_pattern

推荐答案

使用gawk,它支持多字符RS:

gawk 'BEGIN{RS=ORS="End_pattern"}/ef/' file

输出:

Start_pattern
abc
d
ef
ghij 
klm
no End_pattern
Start_pattern
abc
def
hij End_pattern

说明:

# Split records based on the End_pattern
BEGIN{RS=ORS="End_pattern"}

# Print records that contain the search term
/ef/

顺便说一句,出于美观的原因,您可能希望在输出末尾添加换行符:

Btw, for cosmetic reasons you might want to append a newline at the end out the output:

gawk 'BEGIN{RS=ORS="End_pattern"}/ef/;END{printf "\n"}' file


PS:虽然上述解决方案仅适用于gawk,但也可以使用与POSIX兼容的简单awk脚本来实现,这意味着它可以与任何awk一起使用:


PS: While the above solution works with gawk only, it is also possible to achieve that with a simple awk script which is compatible to POSIX, meaning it works with any awk:

awk '{b=b$0"\n"}/End_pattern/{if(b~/ef/){printf "%s",b};b=""}' file

说明:

# Append the current line plus a newline to b(uffer)
{b=b$0"\n"}

# Once End_pattern is found ...
/End_pattern/{
    # Check if the buffer contains the search term
    if(b~/ef/){
        # Print the buffer when the term was found
        printf "%s",b
    }
    # Clear the buffer
    b=""
}

awk '{b=b$0"\n"}/End_pattern/{if(b~/ef/){printf "%s",b};b=""}' file

这篇关于grep匹配模式的行,以及匹配之前和之后直到不同模式的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆