我想清空一个目录中的所有文件。我已经尝试过以下方法:
find myFolderPath/* -exec cat /dev/null > {} ';'
但它不起作用。我该怎么做?
在find -exec
中直接使用重定向符号(>
)是不行的,因为它会在命令运行之前就执行并创建一个名为{}
的文件。要解决这个问题,您需要在一个新的shell中使用sh -c
。
此外,请注意,您不需要使用cat /dev/null > file
来覆盖一个文件。您可以简单地使用> file
。
尝试这个:
find . -type f -exec sh -c '>"{}"' \;
这将实现您想要的功能:
for f in *; do >$f; done
sudo
权限运行此程序? - Bax
find . -type f -exec sh -c '>"$1"' shell {} \;
,以防止文件名中的特殊字符作为脚本的一部分被执行。 - Oylex