Created
January 22, 2015 17:42
-
-
Save Lucretiel/9a9e7b40aceb6a6f1a2e to your computer and use it in GitHub Desktop.
Slightly more useful than grep, but doesn't make you want to punch the computer like sed or cut.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from __future__ import print_function, unicode_literals | |
import argparse | |
import re | |
from sys import stdin | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-o', '--output') | |
parser.add_argument('-a', '--front', action='store_true', help= | |
'Anchor the match at the front of each line') | |
parser.add_argument('-b', '--back', action='store_true', help= | |
'Anchor the match at the back of each line') | |
parser.add_argument('-c', '--lock', action='store_true', help= | |
'Anchor the match at the fron and back of each line') | |
parser.add_argument('-s', '--sep', default='\t', help= | |
'The character with which to separate groups under standard format') | |
parser.add_argument('-i', '--ignore-case', action='store_true') | |
parser.add_argument('regex') | |
parser.add_argument('files', nargs='*') | |
def match(regex, istr, output): | |
for line in istr: | |
line = line.rstrip('\n') | |
match = regex.search(line) | |
if match: | |
print(match.expand(output)) | |
def make_regex(args): | |
base = args.regex | |
if args.lock or args.front: | |
base = '\A' + base | |
if args.lock or args.back: | |
base = base + '\Z' | |
flags = 0 | |
if args.ignore_case: | |
flags = flags | re.I | |
return re.compile(base, flags) | |
def make_output(regex, output, sep): | |
if output: | |
return output | |
elif regex.groups != 0: | |
return sep.join('\g<{0}>'.format(i+1) for i in range(regex.groups)) | |
else: | |
return '\g<0>' | |
def run(regex, output, files): | |
if files: | |
for name in files: | |
print('{0}:'.format(name)) | |
with open(name) as f: | |
match(regex, f, output) | |
else: | |
match(regex, stdin, output) | |
def main(): | |
args = parser.parse_args() | |
regex = make_regex(args) | |
run(regex, make_output(regex, args.output, args.sep), args.files) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment