bash - 如何使用 find 将字符串追加到目录中的每个文件

标签 bash find exec

我试图在跳过 .git 目录的同时将固定字符串附加到文件夹(及其子文件夹)中的每个文件。

我以为这样的事情会奏效

 find . -type f ! -path "./.git/*" -exec "echo \"hello world\" >> {}" \;

如果我用额外的 echo 运行它,它确实会生成看起来正确的命令

bash> find . -type f ! -path "./.git/*" -exec echo "echo \"hello world\" >> {}" \;
echo "hello world" >> ./foo.txt
echo "hello world" >> ./bar.txt
...

当我直接从 shell 运行这些命令时,它们会执行我想要的操作,但是当我从 find 运行它们时,我会得到以下信息:

bash> find . -type f ! -path "./.git/*" -exec "echo \"hello world\" >> {}" \;
find: echo "hello world" >> ./foo.txt: No such file or directory
find: echo "hello world" >> ./bar.txt: No such file or directory
...

但这些文件确实存在,因为当我列出目录时,我得到了这个:

bash> ls
bar.txt  baz.txt  foo.txt  subfolder/

我想我没有引用我需要引用的东西,但我已经尝试了我能想到的一切(双引号和单引号,转义和不转义内引号等...)。

谁能解释一下我的命令有什么问题以及如何实现将固定字符串添加到文件中?

最佳答案

您需要指示 shell 执行此操作:

find . -type f ! -path "./.git/*" -exec sh -c "echo hello world >> {}" \;

关于bash - 如何使用 find 将字符串追加到目录中的每个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19447149/

相关文章:

exec 在期望脚本中不起作用

linux - 如何将状态代码从远程运行的 shell 脚本返回到本地 shell 脚本

linux - 使用 sed 和 IFS 替换 while 循环中的值

bash - 在不知情的情况下从文件中删除扩展名

linux - 编辑 .bash_profile 时权限被拒绝

Unix 查找替换多个文件中的特殊字符

php - 通过 PHP 执行 git 命令

Linux: 'ls' 所有jpg文件在csv中递归

java - 使用Java查找行中的重复值

c++ - execlp 的多行输出