Yan*_*ann 7 bash shell-script files
我有一组文件,所有文件都以约定命名file_[number]_[abcd].bin
(其中 [number] 是驱动器 0 大小范围内的数字,以 MB 为单位)。即有file_0_a.bin
,file_0_b.bin
,file_0_c.bin
和file_0_d.bin
,然后0
将成为1
等等。
文件数在运行时根据分区的大小计算出来。我需要以伪随机方式删除所有已创建的文件。在我需要能够指定的大小块中,即有 1024 个文件的地方,删除 512,然后删除另一个 512。
我目前有以下功能可以执行此操作,我将其称为所需的次数,但它会逐渐不太可能找到存在的文件,直到它可能永远不会完成。显然,这有点不太理想。
我可以用来以随机顺序删除所有文件的另一种方法是什么?
deleteRandFile() #$1 - total number of files
{
i=$((RANDOM%$1))
j=$((RANDOM%3))
file=""
case $j in
0)
file="${dest_dir}/file_${i}_a.bin";;
1)
file="${dest_dir}/file_${i}_b.bin";;
2)
file="${dest_dir}/file_${i}_c.bin";;
3)
file="${dest_dir}/file_${i}_d.bin";;
esac
if ! [[ -f $file ]]; then
deleteRandFile $1
else
rm $file
fi
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编辑:我试图以随机顺序删除,以便我可以尽可能多地分割文件。这是脚本的一部分,首先用 1MB 文件填充驱动器,然后删除它们,一次 1024 个,然后用 1 个 1GB 文件填充“空白”。冲洗并重复,直到你有一些非常碎片化的 1GB 文件。
Sté*_*las 13
如果要删除所有文件,则在 GNU 系统上,您可以执行以下操作:
cd -P -- "$destdir" &&
printf '%s\0' * | # print the list of files as zero terminated records
sort -Rz | # random sort (shuffle) the zero terminated records
xargs -r0 rm -f # pass the input if non-empty (-r) understood as 0-terminated
# records (-0) as arguments to rm -f
Run Code Online (Sandbox Code Playgroud)
如果您只想删除一定数量的匹配正则表达式的内容,您可以在sort
和之间插入如下内容xargs
:
awk -v RS='\0' -v ORS='\0' -v n=1024 '/regexp/ {print; if (--n == 0) exit}'
Run Code Online (Sandbox Code Playgroud)
使用zsh
,您可以执行以下操作:
shuffle() REPLY=$RANDOM
rm -f file_<->_[a-d].bin(.+shuffle[1,1024])
Run Code Online (Sandbox Code Playgroud)
slm*_*slm 11
这是使用find
and的潜在替代方案shuf
:
$ find $destdir -type f | shuf | xargs rm -f
Run Code Online (Sandbox Code Playgroud)
这将找到所有文件$destdir
,然后使用该shuf
命令将它们的顺序打乱,然后将列表传递给以xargs rm -f
进行删除。
要控制删除了多少文件:
$ find $destdir -type f | shuf | head -X | xargs rm -f
Run Code Online (Sandbox Code Playgroud)
-X
要删除的文件数在哪里,例如head -100
.