Skip to content

Instantly share code, notes, and snippets.

@mgronhol
Created September 20, 2013 09:10
Show Gist options
  • Save mgronhol/6635025 to your computer and use it in GitHub Desktop.
Save mgronhol/6635025 to your computer and use it in GitHub Desktop.
Search recursively a directory tree for files that contain a specified string (poor mans grep replacement)
#!/usr/bin/env python
import sys, os
basedir = "."
if len( sys.argv ) > 2:
basedir = sys.argv[1]
string = sys.argv[-1]
def is_in_file( fn, string ):
out = False
with open( fn, 'rb' ) as handle:
txt = handle.read()
out = string in txt
return out
def do_the_crusade( root, string ):
out = []
files = os.listdir( root )
for fn in files:
path = os.path.join( root, fn )
if os.path.isdir( path ):
out.extend( do_the_crusade( path, string ) )
else:
if is_in_file( path, string ):
out.append( path )
return out
files = do_the_crusade( basedir, string )
for fn in files:
print fn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment