在《使用sed命令批量处理Makefile文件的脚本》文中使用sed命令对前文中的Makefile文件进行了替换、追加和删除操作,这篇文章通过使用sed和awk命令对该Makefile文件的某个字符串进行正则匹配查找以及替换。
由于之前在BZ自己CenOS7中的C/C++工程部分Makefile文件有问题(CC变量被赋值为CC := g++
),所以想写个shell脚本批量把Makefile文件出错的部分全部替换成CC := gcc
。
下面的这份shell脚本比较简单,直接运行./sedawkfindreplace1.sh
即可。在for ... in
的Makefile文件遍历中,先利用了awk命令的正则匹配查找、替换操作,然后是sed命令执行正则匹配查找、替换操作。
程序难点应该在于对g++
中的+
号正则匹配。awk的sub
函数的正则替换时,需要对g++
处理成g\+\+
形式,而其它正常都写成g+\+
的形式。
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 | #!/bin/bash # FileName: sedawkfindreplace1.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.2.22 vfhky https://typecodes.com/linux/sedawkfindreplace1.html # https://github.com/vfhky/shell-tools/blob/master/filehandle/sedawkfindreplace1.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 "^CC := g++" by awk command. awk '/CC := g++/{printf( "%s:%d: %s\n", FILENAME, NR, $0) }' ${FILE} #### replace "g++" with "gcc" using awk command. # awk '{sub(/^CC := g++/,"CC := gcc"); print $0}' ${FILE} > ${FILE}.tmp; cp ${FILE}.tmp ${FILE}; rm -rf ${FILE}.tmp #### find "CC := g++" by sed command. # sed -n "/^CC := g++/p" ${FILE} #### Ways recommended: replace "g++" with "gcc" using sed command. # sed -i "s#^CC := g++#CC := gcc#" ${FILE} done exit 0 |
---|
BZ在虚拟机的/home/vfhky/shell目录复制了5个错误的Makefile文件,然后先做正则查找测试,结果如下图所示:
在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]
目前已经把这个脚本放在Github了,地址是https://github.com/vfhky/shell-tools,以后脚本的更新或者更多好用的脚本也都会加入到这个工程中。