3

How do I print n lines before a matched string from a file using python?

man grep

-B NUM, --before-context=NUM

Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given.

I have code for grep -A:

def grepA(word,file,num=0):
    with open(file) as f:
        for line in f:
            if word in line:
                print(line + ''.join(islice(file, num)))
                print('---')
khelwood
  • 55,782
  • 14
  • 81
  • 108

2 Answers2

4

You'll just have to keep a buffer (a list) of the N last lines, then print them when you encounter a match.

context_lines = []
for line in f:
    context_lines.append(line)
    if len(context_lines) > 5:  # Too many lines?
        context_lines.pop(0)  # Pop the first one off.
    if word in line:
        # context_lines already includes the `line` we're looking at
        for ctx_line in context_lines:  
             print(ctx_line)
AKX
  • 152,115
  • 15
  • 115
  • 172
2

You need to cache the lines:

def grepb(word,file, num=0):
    if num == 0:
        print(re.findall(re.compile(word), line)[0])  # https://stackoverflow.com/questions/26659142
    else:
        cache = collections.deque([], num)
        with open(file) as f:
            for line in f:
                cache.append(line)
                if word in line:
                    print('\n'.join(cache))
                    print('---')
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
serv-inc
  • 35,772
  • 9
  • 166
  • 188