Find In Files Using Ruby Or Python
A popular text editor has the following 'find in files' feature that opens in a dialog box: Look For: __searchtext__ File Filter: *.txt; *.htm Start From: c:/docs/2
Solution 1:
I know you said you don't feel like writing it yourself, but for what it's worth, it would be very easy using os.walk
- you could do something like this:
results = []
if regex_search:
p = re.compile(__searchtext__)
fordir, subdirs, subfiles in os.walk('c:/docs/2009'):
for name in fnmatch.filter(subfiles, '*.txt'):
fn = os.path.join(dir, name)
withopen(fn, 'r') as f:
if regex_search:
results += [(fn,lineno) for lineno, line inenumerate(f) if p.search(line)]
else:
results += [(fn,lineno) for lineno, line inenumerate(f) if line.find(__searchtext__) >= 0]
(that's Python, btw)
Solution 2:
Grepper is a Ruby gem by David A. Black for doing exactly that:
g = Grepper.new
g.files = %w{ one.txt two.txt three.txt }
g.options = %w{ B2 } # two lines of before-context
g.pattern = /__search_string__/
g.run
g.results.each do |file, result|
result.matches.each do |lineno, before, line, after|
etc....
I believe it shells out to grep and wraps the results in Ruby objects, which means it takes the same options as grep. Install with:
sudo gem install grepper
Post a Comment for "Find In Files Using Ruby Or Python"