Moving files from nested directories with Unix CLI

The following command flattens current subdirectories moving all files from them to the targetDirectory, keeping directories unchanged
find ./ -type f -mindepth 2 -exec mv -t targetDirectory {} +

You can also remove -mindepth N option, which tells to find files only from subdirectories with nested depth equals or greater then N.
. //depth=1
./subDir //depth=2
./subDir/subSubDir //depth=3

For moving files with names matching to a pattern use -iname pattern option:
find ./ -type f -iname "*.jpeg" -exec mv -t targetDirectory {} +
will move only files ending with “.jpeg”.

If you want to move directories use:
find ./ -type d -exec mv -t targetDirectory {} +

Unfortunately this command doesn’t work on Mac OS X, causing
mv: illegal option -- t
usage: mv [-f | -i | -n] [-v] source target
mv [-f | -i | -n] [-v] source ... directory

It’s because Mac OS X mv utility doesn’t support -t flag, so the command should be slightly changed
find ./ -type f -mindepth 2 -exec mv {} targetDirectory \;

Leave a Reply