Skip to content

Instantly share code, notes, and snippets.

@shanenoi
Last active November 16, 2020 18:30
Show Gist options
  • Save shanenoi/06a07cf29190866762b40ac6d5bae259 to your computer and use it in GitHub Desktop.
Save shanenoi/06a07cf29190866762b40ac6d5bae259 to your computer and use it in GitHub Desktop.
I love using Vim on Terminal. However if you want to open a file, you have to cd to the correct folder, too slow!!! This searching source will help our to open file correctly with some regex patterns (base on name or content search) [support InvertingMatch]
"""
|>>> I WILL PULBLISH THIS SOURCE AS A OFFICAL REPOSITORY AS SOON AS POSSIBLE
|>>> AND HOW TO INSTALL DUE TO EXPORTING AS SESSION VAR IN TERMINAL
# HOW TO USE??
+ python3 % -n name\.txt$ -v danh (search by name)
+ python3 % -n "password:[^ ]+" (search by contect)
"""
from os import popen, system, path, listdir
from sys import argv
from re import search, findall
DEFAULT_EDITOR = "/usr/bin/vi"
GREEN = u"\u001b[32;1m"
BLUE = u"\u001b[34m"
RESET_ALL = u"\u001b[0m"
class Finder(object):
COMMAND = ""
RESULT = []
index = 0
BREAK = ""
def find(self):
command_reader = popen(self.COMMAND)
try:
while (_file:=command_reader.readline()[:-1]):
self.process_result(_file)
except KeyboardInterrupt:
print(self.BREAK)
self.result_behaviour()
def result_behaviour(self):
try:
index = int(input("index: "))
system(f"{DEFAULT_EDITOR} {self.RESULT[index]}")
except (ValueError, IndexError, KeyboardInterrupt):
print(self.BREAK)
def process_result(self, value):
pass
class FindByContent(Finder):
def __init__(self, regex:str, excludes:list=[]):
self.COMMAND = (
"find . -type f " +
(" ".join([f"| grep -v \"{i}\"" for i in excludes]))
)
self.__regex = regex
def process_result(self, value):
lines = open(value, encoding="latin1").read().split("\n")
for num_line, line in enumerate(lines):
result = search(f".{{0,9}}{self.__regex}.{{0,9}}", line)
if result:
print(f"[{self.index:>3}] linenum: {num_line+1} " +
f"of {GREEN+value+RESET_ALL}: " +
f"{BLUE}... {result.group()} ...{RESET_ALL}")
self.RESULT.append(value)
self.index += 1
class FindByName(Finder):
def __init__(self, regex, excludes:list=[]):
self.COMMAND = (
f"find . -type f | grep -P \"{regex}\"" +
(" ".join([f"| grep -v \"{i}\"" for i in excludes]))
)
def process_result(self, value):
print(f"[{self.index:>3}] {value}")
self.RESULT.append(value)
self.index += 1
def main(args):
if args[0] == "-n":
FindByName(args[1], args[2]).find()
elif args[0] == "-c":
FindByContent(args[1], args[2]).find()
if __name__ == "__main__":
args = []
args.append(argv[1])
args.append([])
for ele in argv[2:]:
if ele == "-v":
args.append([])
continue
if ele:
args[-1].append(ele)
args[1] = " ".join(args[1])
args.append([])
main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment