【问题标题】:Using shell to modify files in a folder and all its subfolders使用 shell 修改文件夹及其所有子文件夹中的文件
【发布时间】:2015-03-29 05:04:32
【问题描述】:

我想使用 shell 编写一个程序,该程序给出“FolderA”(本示例中的目录名称)。它会检查 FolderA 中的所有文件以及 FolderA 的所有子文件夹中的所有文件是否有一个单词 (wordA) 并将其替换为另一个单词 (wordB)。

尝试了一些类似的东西 sed -i 's/wordA/wordB/g' 文件夹A/*

但这会产生错误,因为文件夹 A 内还有其他文件夹,并且 sed 在运行到另一个子文件夹时会出错。

我想不出一种方法来使用 find 获取目录和所有子目录中的所有文件,然后对它们执行 sed。有没有办法做到这一点?我对 shell 很陌生。

谢谢!

【问题讨论】:

    标签: bash shell sed find


    【解决方案1】:

    find 将是要走的路。

    bash 替代方案:

    shopt -s globstar
    files=()
    for file in FolderA/**; do   # double asterisk is not a typo
        [[ -f "$file" ]] && files+=("$file")
    done
    sed -i 's/wordA/wordB/g' "${files[@]}"
    

    【讨论】:

      【解决方案2】:

      您可以为此使用find -exec

      find /FolderA -type f -exec sed -i 's/wordA/wordB/g' {} +
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-16
        • 2019-06-19
        • 2012-07-21
        • 1970-01-01
        • 2017-04-06
        • 1970-01-01
        • 2021-11-03
        相关资源
        最近更新 更多