find in files using ruby or python(使用 ruby 或 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/2009
Report: [ ] Filenames [ ]FileCount only
Method: [ ] Regex [ ]Plain Text
事实上,几个流行的文本编辑器都有这个.
In fact, several popular text editors have this.
我想做同样的事情,但使用 python 或 ruby 类而不是文本编辑器.这样,在任何支持 ruby 或 python 的平台上,这种简单的脑残操作都可以从脚本中运行.
I would like to do the same thing but using a python or ruby class instead of a text editor. That way, this same kind of brain-dead simple operation can be run from a script on any platform that supports ruby or python.
问题:我不想自己写这个,所以有没有人知道接受相同或相似的简单输入参数并执行您期望的操作的 ruby 或 python 脚本?
Question: I don't feel like writing this myself, so does anyone know of a ruby or python script that accepts the same or similar easy input args and does what you'd expect?
我正在寻找可以进行强力线性搜索的东西,与索引搜索无关.
I am looking for something that does a brute-force linear search, nothing to do with indexed searches.
推荐答案
我知道你说过你不想自己编写它,但不管它的价值,使用 os.walk<会很容易/code> - 你可以这样做:
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__)
for dir, subdirs, subfiles in os.walk('c:/docs/2009'):
for name in fnmatch.filter(subfiles, '*.txt'):
fn = os.path.join(dir, name)
with open(fn, 'r') as f:
if regex_search:
results += [(fn,lineno) for lineno, line in enumerate(f) if p.search(line)]
else:
results += [(fn,lineno) for lineno, line in enumerate(f) if line.find(__searchtext__) >= 0]
(那是 Python,顺便说一句)
(that's Python, btw)
这篇关于使用 ruby 或 python 在文件中查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!