Created
January 5, 2011 08:21
-
-
Save mkuhn/766052 to your computer and use it in GitHub Desktop.
a small utility for repeatedly (and interactively) running grep on the same file
This file contains 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 | |
import readline | |
import os | |
import sys | |
import re | |
if len(sys.argv) == 1: | |
print >> sys.stderr, "Usage: igrep[.py] file1 [file2 ...]" | |
print >> sys.stderr, "At the prompt, enter a search term to be searched in the specified file(s)." | |
print >> sys.stderr, "As a shortcut, you can search for the n-th field with the search term $n" | |
print >> sys.stderr, "(starting with $1)." | |
print >> sys.stderr, "" | |
print >> sys.stderr, "To exit, press return or CTRL+D." | |
sys.exit() | |
histfile = os.path.join(os.environ["HOME"], ".igrephist") | |
try: | |
readline.read_history_file(histfile) | |
except IOError: | |
pass | |
import atexit | |
atexit.register(readline.write_history_file, histfile) | |
try: | |
line = last_result = "" | |
while True: | |
s = raw_input('> ') | |
# don't search for whitespace | |
if s and not s.strip(): continue | |
# break: empty query | |
if not s: break | |
# shortcut: searching for n-th field of last result with $n | |
m = re.match(r"^\$(\d+)$", s) | |
if m: | |
group = int(m.group(1)) - 1 | |
fields = last_result.split("\t") | |
if len(fields) == 1: | |
fields = last_result.split() | |
if len(fields) <= group: continue | |
s = fields[group] | |
# run grep, saving last line | |
for line in os.popen("grep -i --color=always %s %s " % (s, " ".join(sys.argv[1:])) ): | |
print line, | |
last_result = re.sub(r"\033\[((\d+;)*\d+m|K)", "", line).strip() | |
except EOFError: | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment