grep lines matching a pattern, and the lines before and after the matching until different pattern

前端 未结 4 2162
我寻月下人不归
我寻月下人不归 2021-01-22 02:21
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
4条回答
  •  無奈伤痛
    2021-01-22 02:26

    Just for completeness I add the sed solution here :

    sed -n '/Start_pattern/{:a;N;/End_Pattern/!ba;/ef/p}'
    

    To understand this, you need to think of labels and branches as goto statements

    • If Start_pattern is found execute what is between {...}
    • Define a label a with :a
    • Add the line to the previous record. (N)
    • If End_Pattern is found do not goto label a (!ba)
    • After End_Pattern is found, execute the last part which states that if the full record contains ef, print the record.

提交回复
热议问题