Traversing a keyword for that file

Traversing a keyword for that file

Sometimes encounter hundreds of files to a folder, the file you want to replace a keyword, or a comment line ......
manually modify repeated error-prone
here to use grep / sed / python to simple treatment, reduce labor

step


1. grep to search all files, get a list of files need to be modified, and directed to a file

The following example is to search #define.*0x80files keywords, sorted, de-duplication, redirected to a file

grep -rl "#define.*0x80" |sort | uniq > sub_file_list

2. sed tries to match modify, correct regular expression

The following example is the keyword define.*0x80replaced define.*0x90
Note the use of regular expressions capture

echo "#define METAL_ISA_XL64_EXTENSIONS 0x8000000000000000UL" | sed \'s/\(#define.*\)\(0x80\)\(.*\)/\1 0x90\3/g\'

3. Use the shell script python merging the above steps, all documents are amended

The sed command script right and need to modify the list of files merged into shell scripts

./substitude_KeyforPerLine.py --demo print
./substitude_KeyforPerLine.py -h

substitude_KeyforPerLine.py

#!/usr/bin/python
# -*- coding: UTF-8 -*- 

import argparse
# Create ArgumentParser() object
parser = argparse.ArgumentParser()
# Add argument
# parser.add_argument('--fl', required=True, help='need modified file list')
parser.add_argument('--fl', help='need modified file list')
parser.add_argument('--demo', help='print grep/sed demo')
# parser.add_argument('--total', type=int, help='number of dataset', default=100)

# Print usage
# parser.print_help()
# Parse argument
args = parser.parse_args()

flist = args.fl

def re_demo():
    print("\n");
    print(r'echo "#define METAL_ISA_XL64_EXTENSIONS 0x8000000000000000UL" | sed \'s/\(#define.*\)\(0x80\)\(.*\)/\1 0x90\3/g\'')
    print(r'grep -rl #define.*0x80 |sort | uniq > sub_file_list'+'\n')

def gen_cmd():
    read_list_f=open(flist,'r+')
    write_cmd_f=open('modify_line.sh','w')
    for line in read_list_f.readlines():
        print(r"sed -i -e 's/\(#define.*\)\(0x80\)\(.*\)/\1 0x90\3/g' "+line.strip()) 
        write_cmd_f.write(r"sed -i -e 's/\(#define.*\)\(0x80\)\(.*\)/\1 0x90\3/g' "+line.strip()+"\n")
    read_list_f.close()
    write_cmd_f.close()

if(args.demo == "print"):
    re_demo()
if(flist):
    gen_cmd()

Guess you like

Origin www.cnblogs.com/OneFri/p/11653428.html