Skip to content

Instantly share code, notes, and snippets.

@cou929
Created May 6, 2011 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cou929/959428 to your computer and use it in GitHub Desktop.
Save cou929/959428 to your computer and use it in GitHub Desktop.
grep ChangeLog memo.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
clgrep.py
grep ChangeLog memo.
forked from clgrep on Ruby (http://0xcc.net/unimag/1/)
Kosei Moriyama <cou929@gmail.com>
'''
import re
from optparse import OptionParser
changelog = '/Users/kosei//memo/ChangeLog.txt'
def parse_options():
parser = OptionParser(usage='%prog [options] PATTERN [filename]')
parser.add_option("-i", "--ignore-case", action="store_true",
dest="ignore_case", default=False, help="ignore case")
parser.add_option("-r", "--reverse", action="store_true",
dest="reverse", default=False,
help="print result reversed order")
parser.add_option("-n", "--number", type="int", dest="number", default=-1,
help="get nth result")
parser.add_option("-t", "--without_tab", action="store_true",
dest="without_tab", default=False,
help="without tab on line head")
(options, args) = parser.parse_args()
if len(args) < 1:
parser.print_help()
exit()
return (options, args)
def main():
global changelog
(options, args) = parse_options()
pattern = args[0]
changelog = args[1] if len(args) > 1 else changelog
regexp = re.compile(pattern, re.I) if options.ignore_case else re.compile(pattern)
results = []
buf = ''
for line in open(changelog, 'r'):
if line != "\n":
buf += line
else:
if regexp.search(buf):
results.append(buf)
buf = ''
if buf:
if regexp.search(buf):
results.append(buf)
if options.reverse:
results.reverse()
if options.number != -1 and 0 <= options.number and options.number < len(results):
results = [results[options.number]]
tab_removal = re.compile("^\t", re.M)
if options.without_tab:
tmp = []
for res in results:
tmp.append(tab_removal.sub("", res))
results = tmp
if results:
print "\n".join(results),
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment