import sys
import re
import os
import utils
def main():
files = utils.troll_directories(os.path.normpath(sys.argv[1]))
patterns = utils.convert_patterns(sys.argv[2:])
utils.apply_patterns(files, patterns)
if __name__ == '__main__' : main()
Utils.py:
import re
import os
def convert_patterns(patterns):
results = []
# for each pattern
for pattern in patterns:
# make a regular expression with it
expr = re.compile(pattern)
results.append(expr)
# return the results
return results
def troll_directories(start):
# troll for all the directories like in find
results = []
# Traverse the directory for all the files.
for root, dirs, files in os.walk(start):
for fname in files:
# put the full path into the results
results.append(os.path.join(root, fname))
return results
def apply_patterns(files, patterns):
# for each file in files
for fname in files:
# open the file and read the lines
lines = open(fname).readlines()
for num, line in enumerate(lines):
# for each pattern
for pattern in patterns:
# if pattern found in contents
if pattern.search(lines):
# print file, line number, line
print("{}:{}: {}".format(os.path.join(fname), num+1, line))
Python Find
It is a python based small utility which finds for given regular expression in all the filenames for the given directory and returns them with full pathHow to Use
Just download the package or clone the repo from github.Run the find.py file with source directory and regular expression to search for given as command line argument.
Example : - py find.py '.' '.*.py'
Find,py
#!/usr/bin/env python3 import sys |
import re |
import os |
# Get the start directory. |
start = os.path.normpath(sys.argv[1]) |
# Get the patterns from the command line arguments. |
pattern = sys.argv[2] |
# Convert them to regular expressions. |
expr = re.compile(pattern) |
# Traverse the directory for all the files. |
for root, dirs, files in os.walk(start): |
for fname in files: |
# If a file matches the pattern then print its name. |
if expr.search(fname): |
Another interesting project: https://pypi.org/project/grin |