How to delete random n files from directory?
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
Related videos on Youtube
![Hasan Tıngır](https://i.stack.imgur.com/ULL1u.jpg?s=256&g=1)
Comments
-
Hasan Tıngır almost 2 years
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 ? -
Hasan Tıngır over 5 yearsthis not an answer, no.. this is beyond the answer. this is kind of masterpiece :) thank you brotha :)
-
PerlDuck over 5 years@HasanTıngır You are welcome. Thank you. :-) I appreciate that and am glad I could help you! I enjoyed answering and actually one-line-answers (like just the
find ...
command) aren't well received on AU. Without an explanation nobody without adequate knowledge can tell whether the answer is right/wrong/malicious or how to adapt it to their own problem. -
Jayhello over 5 yearsreally greate answer with detailed explain.