bash - 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 函数,您可以根据自己的条件进行调整:
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
}
推荐阅读
- installation - 在windows中安装odoo
- r - 使用 lapply 向列表的每个元素添加一个新元素
- reactjs - 如何更改模态的宽度?太小了。反应响应模式
- python - 检索始发地和目的地之间的建筑物地址
- security - 如何使用 Gatsby 存储和访问 API 密钥和密码?
- r - 合并R中两个df之间的信息
- javascript - 将 react native web 添加到 react native 项目时出错
- typescript - 连接通用打字稿数组时出错
- android - 为什么 iOS 上的 Flutter 不能从 URL 播放音频文件,而只能从 IP 地址播放?
- javascript - 如何通过ng2-charts angular使用chartJs的自定义渲染方法?