Shell – How to move all files with a certain file extension from subdirectories to a single directory

filesrenameshell

I have a directory that contains many subdirectories. The subdirectories contain lots of types of files with different file extensions. I want to move (not copy) all the files of one type into a new directory. I need all these files to be in the same directory, i.e. it needs to be flat.

(My use case is that I want to move ebooks called *.epub from many directories into a single folder that an EPUB reader can find.)

Best Answer

In zsh, you can use a recursive glob:

mkdir ~/epubs
mv -- **/*.epub ~/epubs/

In bash ≥4, run shopt -s globstar (you can put this in your ~/.bashrc) then the command above. In ksh, run set -o globstar first.

With only POSIX tools, run find:

find . -name '*.epub' -exec mv {} ~/epubs \;
Related Question