How do I delete all of a set of files in a random order?
If you want to delete all the files, then, on a GNU system, you could do:
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
If you want to only delete a certain number of those matching a regexp you'd insert something like this between the sort
and xargs
:
awk -v RS='\0' -v ORS='\0' -v n=1024 '/regexp/ {print; if (--n == 0) exit}'
With zsh
, you could do:
shuffle() REPLY=$RANDOM
rm -f file_<->_[a-d].bin(.+shuffle[1,1024])
Here's a potential alternative using find
and shuf
:
$ find $destdir -type f | shuf | xargs rm -f
This will find all the files in $destdir
and then use the shuf
command to shuffle their order, and then pass the list on to xargs rm -f
for deletion.
To gate how many files are deleted:
$ find $destdir -type f | shuf | head -X | xargs rm -f
Where -X
is the number of files that you want to delete, for example, head -100
.