Bash – Sort Files in All Sub-Directories by Extension

I try to be organised, and put everything in folders where they belong, but, especially at work, this all stops being important after a couple of years, and becomes more difficult to find things especially when backed up. This one liner can resolve all of that by moving each file type to a directory of its own, retaining any duplicate files for further inspection. It may be best to keep a backup of all the original file locations where files of many types come together to make a whole.

Here is my one liner, which needs to be placed in the top directory. One can add as many different file extensions as needed into the variable array EXTS. I have used txt and jpg as example extensions.

If I break it down a bit with comments:

# allows sub directory matching, and moving of hidden files and files in hidden directories

#sets the variable with extensions, from 1 to many

#runs the code for each extension in the variable array EXTS

#do something

#make a directory with the same name as the extension

#move files with the extension in all sub directories to the created top
#level directory of the same name.
# The **/* code which is enabled by the shopt -s globstar command
# allows matching with all sub directories
# The –backup=numbering ensures no files are overwritten and duplicates
# are copied over and renamed

# renames the duplicate files by removing the last character if it
# is a “~” in order to unhide the files. There are better ways of
# doing this 😉

# all done after iterating through each extension type

Leave a Reply

Your email address will not be published. Required fields are marked *