Skip to content

Instantly share code, notes, and snippets.

@larsyencken
Created September 29, 2011 23:28
Show Gist options
  • Save larsyencken/1252222 to your computer and use it in GitHub Desktop.
Save larsyencken/1252222 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# take.py
# bin
#
# Created by Lars Yencken on 2011-09-30.
# Copyright 2011 Lars Yencken. All rights reserved.
#
"""
Take lines from the input until they match a given regex.
"""
import sys
import optparse
import re
def take(regex, until=True):
pattern = re.compile(regex)
write = sys.stdout.write
if until:
for line in sys.stdin:
if pattern.match(line):
break
write(line)
else:
for line in sys.stdin:
if not pattern.match(line):
break
write(line)
#----------------------------------------------------------------------------#
def _create_option_parser():
usage = \
"""%prog [options]
Process stdin line by line until the regex criteria is no longer met."""
parser = optparse.OptionParser(usage)
parser.add_option('--until', action='store', dest='until_regex',
help='Stop at the first line which matches this regex.')
parser.add_option('--while', action='store', dest='while_regex',
help='Stop at the first line which doesn\'t match this regex.')
return parser
def main(argv):
parser = _create_option_parser()
(options, args) = parser.parse_args(argv)
if args or not (bool(options.until_regex) ^ bool(options.while_regex)):
parser.print_help()
sys.exit(1)
regex = options.until_regex or options.while_regex
take(regex, until=bool(options.until_regex))
#----------------------------------------------------------------------------#
if __name__ == '__main__':
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment