background

We often use grep command, but grep command is not very easy to use, so write a Python script to package grep command, make it more friendly, using it can greatly improve efficiency. It allows us to quickly complete complex queries with less input, and it prints out the underlying statements, so let’s take a look at some examples.

example

Simple initial experience of CasE1

I used to use grep to find “documents whose contents contain XX suffix XX” in the current directory, and I wanted it to be case-insensitive and find contents in the directory’s soft links, so I had to write long arguments. Before I want to find the current directory, for example, the name contains the make markdown files, so I have to write: the find. -name “* md” | xargs grep “make” in contrast, all I need now to write: Zgrip will make it for us to generate statements: the find – l. -name “* md” | xargs grep make

Case2 specifies a specific file suffix query

Again, for example, I want to find the current directory, file name contains the make md, so I have to write the find – l. -name “* md” – print | awk ‘{a = “\” “; Print a $0 a} ‘| xargs grep make – I – n – B2 – A2 as a comparison, I now only write: zgrip make -s md

Case3 excludes specific paths

Sometimes, IF I don’t want to find a path, I can exclude that path by using -e, which is the first letter of exclude. It enforces fuzzy queries. I write such a statement: zgrip find – e blog it generates such a complex one statement. The find – l. -name “* md” – print – o – path “* * blog” – the prune | awk ‘{a = “\” “; print a $0 a}’ | xargs grep make -i -n -B2 -A2

use

I will provide the following script as long as you:

  1. Command it as zgrip, without it.pySuffix, usechmod a+x zgrip Become an executable file
  2. Put it in the executable’s lookup path
  3. Use the zgrip keyword and you’ll be happy to use it

Because I like to use markdown to write documents, I default to the find command to find markdown files

Script shows

The shebang command on the first line requires you to specify where your Python3 path should be placed.

#! /usr/bin/env python3
#coding=utf-8
import os,sys


help_txt = """ Use zgrip -h to obtain help. Use zgrip keyword to query md documents containing 'keyword' in the current directory. Use zgrip keyword -d path to query MD documents containing 'keyword' in the specified directory When using zgrip -e to exclude path query, exclude specified path """

######################## Prepare variables
search_dir = ' '
keyword = ' '
suffix = 'NONE'
count = ' '
exclude = ' '

args = sys.argv
if len(args) > 1 and args[1] = ='-h':
    print(help_txt)
if len(args) >= 2:
    keyword = sys.argv[1]

# Capture redundant optional arguments
opt_args = args[2:]
for i in range(len(opt_args)):
    if(opt_args[i] == '-s'):
        suffix = opt_args[i+1]
    if (opt_args[i] == '-d'):
        search_dir = opt_args[i+1]
    if (opt_args[i] == '-c'):
        count = opt_args[i+1]
    if (opt_args[i] == '-e'):
        exclude = opt_args[i+1]

######### Run commands
search_dir = search_dir or '. '
if '+' in suffix:
    suffixes = suffix.split('+')
    # suffix = '.'+ suffix
    suffixes = list(set(suffixes))  # to heavy
    suffixes = [item for item in suffixes]
    suffix = suffixes
else:
    suffix = '.md' if suffix=='NONE' else suffix

count = count or '2'
If the -e parameter exclude is not empty, the query will be executed on the tag
exclude_phrase = '-o -path "*{}*" -prune'.format(exclude) if exclude else ' '


def islist(a) :
    from typing import List
    return isinstance(a, List)

def make_comand() :
    command = []
    if islist(suffix):
        for suffix_part in suffix:
            command_part = 'find -L %s -name "*%s" -print %s | awk \'{a="\\""; print a $0 a}\' | xargs grep "%s" -i -n -B%s -A%s'%(search_dir, suffix_part, exclude_phrase, keyword, count, count)
            command.append(command_part)
    else:
        command = 'find -L %s -name "*%s" -print %s | awk \'{a="\\""; print a $0 a}\' | xargs grep "%s" -i -n -B%s -A%s'%(search_dir, suffix, exclude_phrase, keyword, count, count)
    # example as: find . -iname "*@make*.md"
    ######### Run the command to query the soft link
    return command

def exec_command(command) :
    if islist(command):
        ret = []
        for command_part in command:
            print("the command is: ", command_part)
            ret_part = os.popen(command_part).readlines()
            ret.extend(ret_part)
    else:
        print("the command is: ", command)
        ret = os.popen(command).readlines()
    return ret

def main() :
    command = make_comand()
    ret = exec_command(command)
    for line in ret:
        print(line, end=' ')

if __name__ == '__main__':
    main()








Copy the code

disadvantages

None have been found yet

To do

I can package it as a PIP package and you can install it using PIP directly.