使用 python 递归 grep
我是Python新手,正在努力学习。我正在尝试使用 python 实现一个简单的递归 grep 进行处理,这就是我到目前为止所得到的。
p = subprocess.Popen('find . -name [ch]', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
q = subprocess.Popen('grep searchstring %s', line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print q.stdout.readlines()
有人可以告诉我如何解决这个问题以完成它应该做的事情吗?
I am new to python and trying to learn. I am trying to implement a simple recursive grep using python for processing and here is what I came to so far.
p = subprocess.Popen('find . -name [ch]', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
q = subprocess.Popen('grep searchstring %s', line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print q.stdout.readlines()
Can some one pls tell me how to fix this to do what it is supposed to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该使用 os.walk 函数来浏览文件。使用字符串方法或正则表达式来过滤结果。检查 http://docs.python.org/library/os.html 了解有关如何使用 os.walk。
现在对于 grep 部分,您可以使用
open
函数循环遍历文件。如果您想获取行号,您可能需要查看
enumerate
函数。编辑添加 grep 函数
You should use the
os.walk
function for going through your files. Use string methods or regex for filtering out the results. Check http://docs.python.org/library/os.html for informations about how to use os.walk.Now for the grep part, you can loop over the file with the
open
functionIf you want to get the line numbers, you may want to look into the
enumerate
function.edited to add the grep function
您可以使用 python-textops3 :
示例,从当前目录中的所有 .py 文件中 grep 所有“导入”:
它是纯 python,无需分叉进程。
You can use python-textops3 :
Example, to grep all 'import' in all .py files from current directory :
It is pure python, no need to fork a process.
for
需要与p
对齐,line不行字符串替换,您需要将,
替换为%
通过这些更改和实际搜索值,它可以在我的 OS X 机器上运行。最终脚本:
for
needs to be aligned with thep
above'grep searchstring %s', line
will not do the string replacement, you need to replace the,
with%
With those changes and real search values, it works on my OS X box. Final script:
也许一个例子可以帮助您,命令
find 。 -打印| grep "python"
相当于:Maybe an example can help you, the command
find . -print | grep "python"
is equivalent to this: