Wednesday, August 31, 2011

Recursively Deleting Files by Extension and Empty Directories

Image Source:

Cleaning out some files, I realized I had a lot of unneeded files that were all the same extension. Unfortunately, they were scattered inside of a million folders. What I needed was a command that would go through each folder and delete those files, saving me the effort of doing that. Then, after that, get rid of any empty directories that might have been left behind.

Two commands that can be given at the command line in UbuntuLinux (or Peppermint Linux which is what I was using) work...check further down in this post for how to on other platforms:

To recursively delete files with a particular filename extension:
find /home/mg/Desktop/books -iname "*.html" -exec rm '{}' ';'
In the command above, simply replace HTML with the filename extension you want to get rid of...could be XLS, ODF, PDF, MP3, MOV, whatever.

To delete empty directories, I used this command:
find -depth -type d -empty -exec rmdir {} \;
Both worked great and my hard drive is now free of unwanted files and directories. By the way, these commands run FAST. You blink and it's done. So, be careful.

Update: Interested in copying selected files from directories into one directory on GNU/Linux? Use this command:
find  /home/mg/Desktop/books -iname "*.html" -exec cp {} /home/mg/Desktop/html \;
If you want to move selected files, just use this command:
find  /home/mg/Desktop/books -iname "*.html" -exec mv {} /home/mg/Desktop/html \;

Get Blog Updates via Email!
Enter your email address:
Delivered by FeedBurner

Everything posted on Miguel Guhlin's blogs/wikis are his personal opinion and do not necessarily represent the views of his employer(s) or its clients. Read Full Disclosure

No comments:

Genuine Leadership #4: Gratitude