Xupeng's blog

圆外之大,心向往之

用于查找包含某个关键字的命令的脚本

用于查找包含某个关键字的命令的脚本,时不时用一用可能会有意想不到的收获,找到你非常想用但是你不知道的命令哦:)
#!/usr/bin/python

import os
import sys
import glob

def color_keyword(str, keyword):
    has_output = True
    try:
        from output import red
    except:
        has_output = False
    colored_str = ''
    partials = str.split(keyword)
    for partial in partials[:-1]:
        colored_str += partial + (has_output and red(keyword) or keyword)
    colored_str += partials[-1]

    return colored_str

def main():
    if len(sys.argv) < 2:
        print 'Usage: %s keyword' % sys.argv[0]
        sys.exit(1)

    keyword = sys.argv[1]

    paths = os.environ['PATH'].split(':')
    cmds = []
    for path in paths:
        if path.startswith('~'):
            path = os.path.expanduser(path)
        if not path.endswith('/'):
            path += '/'
        cmds.extend(glob.glob(path + '*'))
    for cmd in cmds:
        dirname, filename = cmd.rsplit('/', 1)
        if keyword in filename:
            print '/'.join([dirname, color_keyword(filename, keyword)])

if __name__ == '__main__':
    main()

Comments