TypeCodes

使用sed和awk查找和替换字符串处理Makefile文件(二)

前文中演示了使用awk和sed命令正则查找和替换Makefile文件的匹配内容,这篇文章依然使用这个Makefile文件作为awk和sed命令正则匹配查找、替换和删除操作。

1 功能需求

由于之前在BZ自己CenOS7中的C/C++工程部分Makefile文件在make clean操作时的语句可以优化,也就是可以把-$(RM) $(ULT_BIN)-$(RM) $(ULT_BIN)这两句写成一句-$(RM) $(ULT_BIN) $(ULT_BIN)

2 shell程序

下面的这份shell脚本比较简单,直接运行./sedawkfindreplace2.sh即可。在for ... in的Makefile文件遍历中,先利用了awk命令的正则匹配查找、替换操作,然后是sed命令执行正则匹配查找、替换以及删除操作。

程序难点应该在于对$符号的正则匹配(它本来表示结尾,所以需要转义),可以看到awk和sed对它的正则匹配形式是不一样的。

另外,脚本中sed命令通过-e参数先执行正则匹配和替换操作,然后执行正则匹配删除操作。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/bin/bash
# FileName:      sedawkfindreplace2.sh
# Description:   Basic usage of sed and awk command such as find and replace words in the regular expression.
# Simple Usage:  ./sedawkfindreplace1.sh
# (c) 2017.3.9 vfhky https://typecodes.com/linux/sedawkfindreplace2.html
# https://github.com/vfhky/shell-tools/blob/master/filehandle/sedawkfindreplace2.sh


# Dir to be handled.
SRC_DIR="/home/vfhky/shell"
# The makefile you want to modify.
SEARCH_NAME="Makefile*"
# The maximum depth of the dirs where files such as Makefile you're dealing with lies in.
MAXDEPTH=10

# Get the target files you want to modify.
ALL_MAKEFILE=$(find ${SRC_DIR} -maxdepth ${MAXDEPTH} -type f -name "${SEARCH_NAME}")


# Traverse the target files.
for FILE in ${ALL_MAKEFILE}
do
    #### Ways recommended: find "-$(RM) $(ULT_BIN)" by awk command.
    #awk '/-\$\(RM\) \$\(ULT_BIN\)/{printf( "[%s:%d]: %s\n", FILENAME, NR, $0) }' ${FILE}

    #### replace "-$(RM) $(ULT_BIN)" with "-$(RM) $(ULT_BIN) $(ULT_LIBS)" using awk command.
    # awk '{sub(/-\$\(RM\) \$\(ULT_BIN\)/,"-\$\(RM\) \$\(ULT_BIN\) \$\(ULT_LIBS\)"); print $0}' ${FILE} > ${FILE}.tmp; cp ${FILE}.tmp ${FILE}; rm -rf ${FILE}.tmp


    #### find "-$(RM) $(ULT_BIN)" by sed command.
    #sed -n "/-\$(RM) \$(ULT_BIN)/p" ${FILE}

    #### Ways recommended: Step1. replace "-$(RM) $(ULT_BIN)" with "-$(RM) $(ULT_BIN) $(ULT_LIBS)" using sed command.
    #### Step2. delete the line contains the words "-$(RM) $(ULT_LIBS)".
    sed -i -e "s#-\$(RM) \$(ULT_BIN)#-\$(RM) \$(ULT_BIN) \$(ULT_LIBS)#" -e "/-\$(RM) \$(ULT_LIBS)/d" ${FILE}
done

exit 0

3 脚本测试

BZ在虚拟机的/home/vfhky/shell目录复制了5个错误的Makefile文件,然后先做正则查找测试,结果如下图所示:

使用sed和awk查找和替换字符串处理Makefile文件(二)

4 Linux find 命令中正则

find命令的某个参数使用正则,那么最好对这个对数加上双引号,正如上面的代码"${SEARCH_NAME}"所示,否则会出现下面的错误:

find: paths must precede expression: Makefile1
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

5 脚本管理

目前已经把这个脚本放在Github了,地址是https://github.com/vfhky/shell-tools,以后脚本的更新或者更多好用的脚本也都会加入到这个工程中。

打赏支持

Comments »