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('---')