首页 > 解决方案 > 通过 shellscript 编辑文件?

问题描述

我需要解压缩一个文件,并且对于该文件中的每个文档,我需要对注释进行更正(这些文件是用 C 编写的)。我对如何为文件中的每个文档执行此操作有点困惑(我不知道文档的数量或它们的名称),是否可以在文件夹中编写一个 for 循环来打开每个单独记录,然后在 shellscript 中编辑它们?

我对 sed 和 awk 之间的区别以及我应该在这里使用哪个感到有些困惑。我需要编辑评论(以 // 开头)并相信我应该使用 awk 但不太确定。

我的伪代码(到目前为止)就是这样

unzip $1
edit_comment(){
    cat file1 file2 ... filen > total.txt
    *some awk command that will search for all instances of // and replace the text on that line (after 
    the //) with a new comment*
}

谢谢!

标签: bashawkwindows-subsystem-for-linux

解决方案


我相信您正在寻找如何使用 awk 或 sed 递归查找/替换字符串

假设:
- 参数$1是一些folder.tar.gz或- 解压缩存档中包含注释archive.zipblah.bz4
所有文件都应更改

dir=$(echo $1 | sed 's#\..*##')
find $dir -type f -print0 | xargs -0 sed -i 's#//old comment #//new comment#'

推荐阅读