Skip to content

Instantly share code, notes, and snippets.

@towersvault
Created January 9, 2019 19:09
Show Gist options
  • Save towersvault/09c4814d73c445e91ddf5bd696dc239a to your computer and use it in GitHub Desktop.
Save towersvault/09c4814d73c445e91ddf5bd696dc239a to your computer and use it in GitHub Desktop.
A script that checks for a given phrase in all text based files in (and deeper) in a directory. Best use case would be with moving a website from one domain to another and then having to deal with static URLs.
import glob
def get_files(scan_folder):
"""
Gets all the files deeper in from the provided scan_folder.
Does a recursive "search" using glob.
"""
if scan_folder[:-1] != '/':
scan_folder += '/'
return [filename for filename in glob.iglob(scan_folder + '**/*.*', recursive=True)]
def search_for_phrase(filename, phrase, ignore_case=False):
"""
A line for line scan gets done on a normal text file to check if a line contains the provided phrase.
"""
try:
content = [x.strip() for x in open(filename).readlines()]
for line_number in range(0, len(content)):
if (content[line_number].lower() if ignore_case else content[line_number]).__contains__((phrase.lower() if ignore_case else phrase)):
print(f'FN: {filename}, LN: {line_number + 1}\nContent: {content[line_number]}\n')
except:
pass
if __name__ == '__main__':
base_folder = ''
search_phrase = ''
files = get_files(base_folder)
for f in files:
search_for_phrase(f, search_phrase, ignore_case=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment