[英]How to delete the contents of all the files in a directory
Under /tmp/REPORTS
I have a hundred files. 在/tmp/REPORTS
我有一百个文件。 What I want to do is erase the contents of each file in /tmp/REPORTS
(not delete them). 我想要做的是擦除/tmp/REPORTS
中每个文件的内容(而不是删除它们)。 So I tried the following, but I get this error: 所以我尝试了以下操作,但出现此错误:
cp /dev/null /tmp/REPORTS/*
cp: Target /tmp/REPORTS/….. must be a directory
Usage: cp [-f] [-i] [-p] [-@] f1 f2
cp [-f] [-i] [-p] [-@] f1 ... fn d1
cp -r|-R [-H|-L|-P] [-f] [-i] [-p] [-@] d1 ... dn-1 dn
How can I clear the contents of all the files in the directory? 如何清除目录中所有文件的内容?
Assuming that you mean you want to truncate the contents of each file, you can do this: 假设您要截断每个文件的内容,可以执行以下操作:
for file in /tmp/REPORTS/*; do > "$file"; done
This will clear the contents of each file in the directory. 这将清除目录中每个文件的内容。
As gniourf_gniourf has suggested in the comments above, there is a GNU tool truncate
that can do the job for you as well: 正如gniourf_gniourf在上面的注释中所建议的那样,有一个GNU工具truncate
也可以为您完成这项工作:
truncate --size 0 /tmp/REPORTS/*
This will possibly be quicker than looping through the files manually. 这可能比手动循环浏览文件更快。
The question appears to be asking for what is termed a "secure erase". 问题似乎是在询问所谓的“安全擦除”。
While you cannot cp /dev/null
, you could get the effect you are asking about using dd
. 虽然您无法cp /dev/null
,但是您可以得到您要求使用dd
的效果。 Here is a script to illustrate: 这是一个脚本来说明:
#!/bin/sh
for name in $*
do
test -h "$name" && continue
test -f "$name" || continue
blocks=`ls -s "$name" | awk '{print $1; }'`
dd if=/dev/zero of="$name" count=$blocks
done
The script 剧本
dd
to copy 0's from the special device /dev/zero
. 最后,它使用dd
从特殊设备/dev/zero
复制0。 This relies on dd
and ls
having the same notion of blocksize (which appears to be the case). 这依赖于dd
和ls
具有相同的块大小概念(似乎是这种情况)。 It also assumes that the filesystem does not reallocate blocks for a given file, ie, that they can be reliably overwritten in-place. 它还假定文件系统没有为给定文件重新分配块,即可以可靠地就地覆盖它们。 If you want a better guarantee, there are other solutions, eg, this discussion of Secure Erase in UNIX 如果需要更好的保证,还有其他解决方案,例如,关于UNIX中安全擦除的讨论
you can use this 你可以用这个
for remove 删除
find /tmp/REPORTS/ -type f -name "*.*" -exec rm -rf {} \;
or move them to some where you want for cp 或将它们移动到您想要使用cp的位置
find /tmp/REPORTS/ -type f -name "*.*" -exec cp {} \tmp\{} \;
for mv 对于MV
find /tmp/REPORTS/ -type f -name "*.*" -exec mv {} \dev\null \;
Try this instead: 尝试以下方法:
$ find /tmp/REPORTS/ -type f -exec cat /dev/null > {} \\;
Or if you have a large number of files, try using \\+
instead of \\;
或者,如果您有大量文件,请尝试使用\\+
代替\\;
for a more efficient commandline. 以获得更高效的命令行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.