Skip to content

Instantly share code, notes, and snippets.



Created Nov 26, 2017
What would you like to do?
#!/usr/bin/env python
import argparse
import re
import sys
parser = argparse.ArgumentParser(description=
'''Filter some text with a regex, allowing matches to span multiple lines.
This tool is based on some ideas from Rob Pike's Sam editor:
parser.add_argument('-i', dest='ignore_case', action='store_true', help='ignore case')
parser.add_argument('-s', dest='sort', action='store_true', help='sort matches')
parser.add_argument('-r', dest='reverse', action='store_true', help='reverse (also works with sort)')
parser.add_argument('pattern', type=str, nargs=1)
parser.add_argument('filenames', type=str, nargs='*')
args = parser.parse_args()
pat = args.pattern[0]
rxflags = re.DOTALL
if args.ignore_case:
rxflags |= re.IGNORECASE
rx = re.compile(pat, rxflags)
if len(args.filenames) == 0:
contents =
contents = ''
for fn in args.filenames:
with open(fn) as f:
contents +=
matches = rx.findall(contents)
if args.sort:
if args.reverse:
for m in matches:
whole = m
if isinstance(m, tuple):
whole = m[0]
if whole.strip():
print whole
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.