How to grep lines between two patterns in a big file with python

前端 未结 5 1994
青春惊慌失措
青春惊慌失措 2021-01-03 12:45

I have a very big file, like this:

[PATTERN1]
line1
line2
line3 
...
...
[END PATTERN]
[PATTERN2]
line1 
line2
...
...
[END PATTERN]

I need to extract

5条回答
  •  感动是毒
    2021-01-03 13:18

    i would go with a generator-based solution

    #!/usr/bin/env python    
    start_patterns = ('PATTERN1', 'PATTERN2')
    end_patterns = ('END PATTERN')
    
    def section_with_bounds(gen):
      section_in_play = False
      for line in gen:
        if line.startswith(start_patterns):
          section_in_play = True
        if section_in_play:
          yield line
        if line.startswith(end_patterns):
          section_in_play = False
    
    with open("text.t2") as f:
      gen = section_with_bounds(f)
      for line in gen:
        print line
    

提交回复
热议问题