Last active
March 29, 2020 22:27
-
-
Save ssomnath/7f7a97ec2f49b72ddf15e6df02ee3ab3 to your computer and use it in GitHub Desktop.
Finds locations of all occurences of a string within a directory or code project
This file contains 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
import os | |
def search_in_file(file_path, target_string, match_case=False, abs_paths=False): | |
if not match_case: | |
target_string = target_string.lower() | |
_, file_name = os.path.split(file_path) | |
with open(file_path) as myFile: | |
try: | |
for num, line in enumerate(myFile.readlines()): | |
if not match_case: | |
line = line.lower() | |
if target_string in line: | |
temp = file_name | |
if abs_paths: | |
temp = os.path.abspath(file_path) | |
print('{} : {} : {}'.format(temp, num, line)) | |
except UnicodeDecodeError: | |
print('************** Could not read: ' + file_path) | |
def search_all_files(root_path, target_string, ignore_folders=[], target_ftypes=[], | |
match_case=False, abs_paths=False): | |
for item in os.listdir(root_path): | |
item = os.path.join(root_path, item) | |
if os.path.isdir(item): | |
if item not in ignore_folders: | |
search_all_files(item, target_string, match_case=match_case, abs_paths=abs_paths, | |
ignore_folders=ignore_folders, target_ftypes=target_ftypes) | |
else: | |
if any([item.endswith(ftype) for ftype in target_ftypes]): | |
search_in_file(item, target_string) | |
search_all_files(os.path.abspath('.'), 'cookbook', | |
ignore_folders=['.git', '.idea', '.cache', 'jupyter_notebooks', 'data', 'pycroscopy', 'tests'], | |
target_ftypes=['.py', '.txt', '.rst']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
grep -rnw '/path/to/somewhere/' -e 'pattern'