Skip to content

Instantly share code, notes, and snippets.

@akarca
Created February 12, 2022 18:17
Show Gist options
  • Save akarca/ba76c30191292b9cfeaddd4d5601dc26 to your computer and use it in GitHub Desktop.
Save akarca/ba76c30191292b9cfeaddd4d5601dc26 to your computer and use it in GitHub Desktop.
def grep(text, match, after=0, before=0):
"""
Return matched lines in given text as a list. Similar to grep function but a simple one.
"""
idx = []
lines = text.split("\n")
for i, line in enumerate(lines):
if str(match) not in line:
continue
idx.append(i)
if after:
idx += range(i + 1, i + 1 + after)
if before:
idx += range(i - before, i)
idx = sorted(list(set(idx)))
return [lines[i] for i in idx]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment