shellnotes/util/notegrep/m.py

63 lines
2.1 KiB
Python
Raw Normal View History

2021-07-02 11:51:49 +02:00
#!/usr/bin/env python3
#shellnotes - m.py
#(C) Dimitris Marakomihelakis
#Released under the "All rights reserved" category. See the RIGHTS.txt file
#in /docs/github/ for its full text.
2021-07-02 09:50:21 +02:00
import sys
2021-07-02 11:45:43 +02:00
import os.path
from os import path
import subprocess
2021-07-02 17:19:01 +02:00
from subprocess import check_output
import re
2021-07-02 09:50:21 +02:00
class Multi():
def __init__(self, patterns, files):
self.patterns = patterns
self.files = files
2021-07-02 17:43:27 +02:00
def remove_duplicates(self):
self.patterns, self.files = list(dict.fromkeys(self.patterns)), list(dict.fromkeys(self.files))
2021-07-02 18:13:27 +02:00
def remove_spaces(self):
self.patterns, self.files = [elem.strip(' ') for elem in self.patterns], [elem.strip(' ') for elem in self.files]
2021-07-02 10:41:52 +02:00
def print_matches(self):
2021-07-02 11:45:43 +02:00
2021-07-02 10:41:52 +02:00
for file in self.files:
2021-07-02 17:19:01 +02:00
try:
if file == "": return 0
print("\n"+file if path.exists('Notes/'+file) else f"\n{file} (not found):\n-", flush=True)
print("=" * len(file) if path.exists('Notes/'+file) else "", flush=True)
2021-07-02 11:45:43 +02:00
2021-07-02 17:19:01 +02:00
for pattern in self.patterns:
if pattern == "": return 0
with open('Notes/'+file, 'r') as f:
for line in f:
if re.search(pattern, line):
2021-07-03 09:26:22 +02:00
out = os.system(f"""echo -n "'\033[1;35;40m{pattern}\033[0;37;0m'": && grep -n --color=always {pattern} Notes/{file}""")
2021-07-02 17:19:01 +02:00
#bug: pattern is generated multiple times
2021-07-02 17:19:01 +02:00
except FileNotFoundError: pass
2021-07-02 11:45:43 +02:00
def main():
try:
newMulti = Multi(sys.argv[1].split(','), sys.argv[2].split(','))
2021-07-02 17:43:27 +02:00
newMulti.remove_duplicates()
2021-07-02 18:13:27 +02:00
newMulti.remove_spaces()
2021-07-02 11:45:43 +02:00
newMulti.print_matches()
except IndexError:
patterns = input("Enter patterns, separated by a comma: ")
files = input("Enter files, separated by a comma: ")
newMulti = Multi(patterns.split(','), files.split(','))
2021-07-02 17:43:27 +02:00
newMulti.remove_duplicates()
2021-07-02 18:13:27 +02:00
newMulti.remove_spaces()
2021-07-02 11:45:43 +02:00
newMulti.print_matches()
2021-07-02 09:50:21 +02:00
2021-07-03 09:26:22 +02:00
if __name__ == "__main__":
2021-07-02 11:45:43 +02:00
main()