前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用sed和awk查找和替换字符串处理Makefile文件(一)

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

作者头像
typecodes
发布2024-03-29 14:43:24
1470
发布2024-03-29 14:43:24
举报
文章被收录于专栏:typecodestypecodes

《使用sed命令批量处理Makefile文件的脚本》文中使用sed命令对前文中的Makefile文件进行了替换、追加和删除操作,这篇文章通过使用sed和awk命令对该Makefile文件的某个字符串进行正则匹配查找以及替换。

1 功能需求

由于之前在BZ自己CenOS7中的C/C++工程部分Makefile文件有问题(CC变量被赋值为CC := g++),所以想写个shell脚本批量把Makefile文件出错的部分全部替换成CC := gcc

2 shell程序

下面的这份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

3 脚本测试

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

使用sed和awk查找和替换字符串处理Makefile文件(一)
使用sed和awk查找和替换字符串处理Makefile文件(一)
4 Linux find 命令中正则

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

代码语言:javascript
复制
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,以后脚本的更新或者更多好用的脚本也都会加入到这个工程中。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-02-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1 功能需求
  • 2 shell程序
  • 3 脚本测试
  • 4 Linux find 命令中正则
  • 5 脚本管理
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档