Skip to content

Instantly share code, notes, and snippets.

@AlexandrLucas
Last active August 5, 2021 12:12
Show Gist options
  • Save AlexandrLucas/dad5c471e066b75f06e44d75589c4016 to your computer and use it in GitHub Desktop.
Save AlexandrLucas/dad5c471e066b75f06e44d75589c4016 to your computer and use it in GitHub Desktop.
(Hacky) recursive grep in Python
#!/usr/bin/env python3
import os
user_input = input('What is the name of your directory?\n')
searchstring = input('What string are you trying to find?\n')
def recr(dir):
for fname in os.listdir(dir):
rel_fname = dir + os.sep + fname
if os.path.isfile(rel_fname):
file_search(rel_fname, searchstring)
elif os.path.isdir(rel_fname):
recr(rel_fname)
def file_search(fname, searchstring):
# Full path
try:
f = open(fname, 'r')
if searchstring in f.read():
print('Found string in file: %s' % fname)
f.close()
except Exception:
pass
recr(user_input)
print('Search complete')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment