Manager: Hey, I need your help, I have couple of images that are taking a lot of space on my PC, I want to delete them. How can I do that?
Developer: Well that should be simple. Here, you go. This looks for all files with .png
extension in the current directory and its subdirectories (using -R
flag), then pipes those file names to rm
command to delete them.
ls -R | grep ".png$" | xargs rm
Manager: Nice, but wait. This will delete all the png
files in the current directory and its subdirectories. I only want to delete in specific directories.
Developer: Okay, that should be easy as well.
ls -R dir1 dir2 | grep ".png$" | xargs rm
Manager: This only selects .png
but I also have image of .jpg
and .jpeg
files. I want to delete them too.
Developer: Okaay, this getting complicated a little bit. I think I can do that with find
command, think that is much safer.
# command 1
# {} is a placeholder for matched file
# {} \; means execute rm command for each matched file
# the -o flag means OR operator and \( means brackets are escaped
# and used to club together the expression using or operator
find dir1 dir2 -type f \( -name "*.png" -o -name "*.jpg" -o -name "*.jpeg" \) -exec rm {} \;
# command 2
# -E enables extended regex
# rm {} + means rm file1 file2 file3 ....
find -E dir1 dir2 -type f -regex ".*/.*(png|jpg|jpeg)" -exec rm {} +
Manager: Much better, now narrow down the files to only those files which were created in last 7 days.
Developer: Okay, is that it? Or are there any more conditions?
Manager: Yeah, and one more condition, files should be at least 5 MB in size.
Developer: I see, is that it?
Manager: Yeah, think so. Can you do that?
Developer: Sure. This should do the trick.
find -E dir1 dir2 -type f -regex ".*/.*(png|jpg|jpeg)" -ctime -7 -size +5M -exec rm {} +
Developer: To explain in more detail, find
command is of the form: find [flags] [path(s) to search in] [expression(s) or filter(s)] [actions]
.