Created
September 20, 2013 09:10
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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