如何以随机顺序删除所有一组文件?

Yan*_*ann 7 bash shell-script files

我有一组文件,所有文件都以约定命名file_[number]_[abcd].bin(其中 [number] 是驱动器 0 大小范围内的数字,以 MB 为单位)。即有file_0_a.binfile_0_b.binfile_0_c.binfile_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

这是使用findand的潜在替代方案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.

  • 至少在一般情况下,这个答案是不安全的。`find` 输出由换行符分隔的文字字符串,`xargs` 读取一个 *shell 引用的、空格分隔的 * 名称列表作为输入。输入中的恶意名称可以诱使它删除与您打算删除的内容截然不同的内容。 (2认同)
  • @R - 查看 OP 使用的文件名格式的要求。鉴于此,这是完全安全的! (2认同)