使用python递归grep [英] recursive grep using python

查看:194
本文介绍了使用python递归grep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,想学习。我想实现一个简单的递归grep使用python进行处理,这是我到目前为止。



pre $ sub code $ p $ subprocess.Popen('find。-name [ch]',shell = True,stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
for p.stdout.readlines()中的行:
q = subprocess.Popen('grep searchstring%s',line,shell = True,stdout = subprocess.PIPE,stderr = subprocess.STDOUT)
print q.stdout.readlines()

有人可以请告诉我如何解决这个问题,做它应该做的事情?

解决方案

您应该使用 os .walk 函数来检查你的文件。使用字符串方法或正则表达式来过滤结果。有关信息,请查阅 http://docs.python.org/library/os.html 。关于如何使用os.walk。

  import os 
import re

def findfiles (路径,正则表达式):
regObj = re.compile(正则表达式)
res = []
for os.walk(路径)中的root,dirs,fnames:
for fname在fnames中:
if regObj.match(fname):
res.append(os.path.join(root,fname))
return res

print findfiles ('。',r'my?(reg | ex)')

,你可以用打开函数来遍历该文件。

  def grep (文件路径,正则表达式):
regObj = re.compile(正则表达式)
res = []
打开(文件路径)作为f:
for f:
如果regObj.match(行):
res.append(line)
return res

如果哟你想获得行号,你可能想看看枚举函数。



编辑过添加grep函数

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?

解决方案

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.

import os
import re

def findfiles(path, regex):
    regObj = re.compile(regex)
    res = []
    for root, dirs, fnames in os.walk(path):
        for fname in fnames:
            if regObj.match(fname):
                res.append(os.path.join(root, fname))
    return res

print findfiles('.', r'my?(reg|ex)')

Now for the grep part, you can loop over the file with the open function

def grep(filepath, regex):
    regObj = re.compile(regex)
    res = []
    with open(filepath) as f:
        for line in f:
            if regObj.match(line):
                res.append(line)
    return res

If you want to get the line numbers, you may want to look into the enumerate function.

edited to add the grep function

这篇关于使用python递归grep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆