How to delete random n files from directory?
I have a uploads directory and I want to delete random 1000 images from it. How can I do that with command ?
I am able to delete single with rm
but it tooks long.. Is there any way to bulk delete on ubuntu ?
Solution 1:
find /uploads -maxdepth 1 -type f -name "*.jpg" -print0 | \
head -z -n 1000 | xargs -0 rm
The find
command finds any files (-type f
) named *.jpg
(-name "*.jpg"
) in the directory /uploads
and does NOT recurse into subdirectories (-maxdepth 1
) (which it usually does). It then prints the filenames with \0
as a separator in-between. This is necessary as the filenames might contain weird characters (like spaces and such).
That output is fed into the head
command. It reads the first 1000 "lines" (-n 1000
) which are separated by \0
(-z
).
Eventually these 1000 "lines" (=filenames) are fed into xargs
which as well expects the "lines" to be separated by \0
(-0
) and then executes rm
with all those 1000 lines as parameters.
If you just want to preview the result, change the command to
find /uploads -maxdepth 1 -type f -name "*.jpg" -print0 | \
head -z -n 1000 | xargs -0 echo rm
i.e. replace xargs … rm
with xargs … echo rm
. Maybe also replace the 1000
with 10
for the preview.
Disclaimer: I don't know how the files printed by find
are sorted, but at least it is not some apparent attribute (like name or age) and looks random. If you really want to pick 1000 random files, you would need to insert a sort -R
to sort randomly (again with -z
for the \0
delimiter):
find /uploads -maxdepth 1 -type f -name "*.jpg" -print0 | \
sort -z -R | head -z -n 1000 | xargs -0 rm