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?
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:
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
Maybe an example can help you, the command
find . -print | grep "python"
is equivalent to this: