首页 > 解决方案 > Bash 递归地将一个文件附加到另一个文件

问题描述

我编写了一个 bash 函数来在设置新项目时自动执行一系列操作。下面是一个示例目录结构。我有两个项目和一些模板文件和代码片段。

~/projects
├── template_files/
│   ├── folder_A1/
│   ├── file_A2
│   └── ...
│
├── codepieces/
│   ├── file_X
│   └── ...
│
├── project1/
│   ├── file_X
│   └── ...
│
├── project2/
│   ├── file_X
│   └── ...

我的 bash 函数中的一项操作将整个 template_files 结构复制(添加/覆盖)到项目中。

$ cp -a template-files/. projectX

我想对我的代码片段做同样的事情,除了添加或替换之外,我想将内容附加到现有文件中(而不是像那样一一进行$ echo codepieces/file_X >> projectX/file_x

所以我正在寻找将功能$ cp -a$ echo codepieces/file_X >> projectX/file_x. project1 的结果如下:

~/project1
├── folder_A1/
├── file_A2
├── file_X (original code is appended with codepiece)
└── ...

标签: bash

解决方案


一个简单的 bash 函数,您可以根据自己的条件进行调整:

cp-a_with-append(){
    if [ ! -d "$1" ] || [ ! -d "$2" ]; then
        echo 1>&2 Usage: cp-a_with_append SRCDIR DESTDIR
    else
        ( cd "$1" && find ) | while read p; do
            pin="$1/$p"
            pout="$2/$p"
            # [ -d "$pin" ] && mkdir -p "$pout"
            [ -f "$pin" ] && [ -f "$pout" ] && cat "$pin" >> "$pout"
            touch -cr "$pin" "$pout"
        done
    fi
}

推荐阅读