#!/usr/bin/env python import sys,os,re Green="\033[32;1m" Red="\033[31;1m" Reset="\033[0m" key_list="1234567890qwertyuiop" class getch: def get(self): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch def printerr(s): sys.stderr.write(s+"\n") sys.stderr.flush() # Print help if len(sys.argv)==1 or sys.argv[-1]=="-h": printerr("Guess cd: Find first match in folder, interactive if multiple matches\n Arguments: [dir/]pattern_to_match_folders") if sys.argv[-1]=="-h": sys.exit(0) pattern=".".join(sys.argv[1:]) pat_base=os.path.basename(pattern) pat_dir=os.path.dirname(pattern) if pat_dir=="": pat_dir="." if not os.path.exists(pat_dir): printerr("%s: %sNo such folder%s"%(pat_dir,Red,Reset)) sys.exit(1) # list sub-folders in the folder current_folders=[d for d in os.listdir(pat_dir) if os.path.isdir(d)] current_folders=[d for d in current_folders if not d.startswith(".")] current_folders.sort() # find matches match_case=re.compile(".*"+pat_base+".*") repl_case=re.compile("("+pat_base+")") matching_folders=[d for d in current_folders if match_case.match(d)] matches=[repl_case.sub("%s\g<1>%s"%(Green,Reset),d) for d in matching_folders] # no matches, try case insensitive if len(matching_folders)==0: match_nocase=re.compile(".*"+pat_base+".*",re.I) repl_nocase=re.compile("("+pat_base+")",re.I) matching_folders=[d for d in current_folders if match_nocase.match(d)] matches=[repl_nocase.sub("%s\g<1>%s"%(Green,Reset),d) for d in matching_folders] # One match, print and return if len(matching_folders)==1: printerr(matches[0]) print(os.path.join(pat_dir,matching_folders[0])) sys.exit(0) # No matches if len(matching_folders)==0: printerr("%sno matches%s"%(Red,Reset)) sys.exit(1) # Many matches, ask the user for folder index for i,m in enumerate(matches[0:len(key_list)]): printerr(key_list[i]+": "+m) if len(matches)>len(key_list): printerr("Skipping the rest...") import termios,tty ch=getch() key_in=ch.get() try: key_index=key_list.index(key_in) key_match=matching_folders[key_index] except (ValueError,IndexError) as err: printerr("%s'%s' Not in the list%s"%(Red,key_in,Reset)) sys.exit(1) print(os.path.join(pat_dir,key_match))