bash 如何使用 find 将字符串附加到目录中的每个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19447149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use find to append a string to every file in a directory
提问by Carcophan
I'm trying to append a fixed string to each file in a folder (and its subfolders) whilst skipping the .git directory.
我试图将一个固定字符串附加到文件夹(及其子文件夹)中的每个文件,同时跳过 .git 目录。
I expected that something like this would work
我希望这样的事情会奏效
find . -type f ! -path "./.git/*" -exec "echo \"hello world\" >> {}" \;
and if I run it with an additional echo it does generate commands that look right
如果我用额外的 echo 运行它,它会生成看起来正确的命令
bash> find . -type f ! -path "./.git/*" -exec echo "echo \"hello world\" >> {}" \;
echo "hello world" >> ./foo.txt
echo "hello world" >> ./bar.txt
...
and those commands do what I want when I run them directly from the shell but when I run it from find I get this:
当我直接从 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
...
but those files do exist because when I list the directory I get this:
但这些文件确实存在,因为当我列出目录时,我得到了这个:
bash> ls
bar.txt baz.txt foo.txt subfolder/
I guess that I'm not quoting something I need to but I've tried everything I can think of (double and single quote, escaping and not escaping the inner quotes etc...).
我想我没有引用我需要的东西,但我已经尝试了我能想到的一切(双引号和单引号,转义而不是转义内部引号等......)。
Can someone explain what is wrong with my command and how to achieve the the addition of the fixed string to the files?
有人可以解释我的命令有什么问题以及如何实现将固定字符串添加到文件中吗?
回答by devnull
You need to instruct the shell to do it:
您需要指示外壳执行此操作:
find . -type f ! -path "./.git/*" -exec sh -c "echo hello world >> {}" \;
回答by gentoomaniac
do it like this
像这样做
find . -type f ! -path "./.git/*" -exec echo "hello world" >> {} \;
and it should work fine.
它应该可以正常工作。
find tries to execute a file which is called echo "hello world" >> ./foo.txt
etc.
find 尝试执行一个名为echo "hello world" >> ./foo.txt
etc的文件。