
在“使用sed命令批量处理Makefile文件的脚本”一文中,使用sed命令替换,附加和删除上一篇文章中的Makefile文件. 本文通过使用sed和awk命令来使用Makefile文件之一. 定期匹配搜索和替换字符串.
因为BZ自己的CenOS7的C / C ++项目部分中的Makefile存在问题(CC变量分配为CC: = g ++)linux awk替换字符串,所以我想编写一个Shell脚本来替换Makefile文件中的所有错误为CC: = gcc.

以下shell脚本相对简单,只需运行./sedawkfindreplace1.sh. 在Makefile文件的for ... in遍历中,首先使用awk命令的常规匹配搜索和替换操作,然后由sed命令执行常规匹配搜索和替换操作.
程序的难点应该是匹配g ++中的+号. 在常规替换awk子函数时,需要将g ++处理为g \ + \ +的形式linux awk替换字符串,而其他普通函数则以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 youre 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://www.pc-fly.com/a/jisuanjixue/article-282916-1.html
我相信我们的政府一定能有不战而屈人之兵的智慧
_)