Ubuntu – How to dissolve all subfolders

command linedirectoryfindmv

Is there a command line one-liner to move all the contents of all the direct subfolders of a folder to the folder itself and deleting the subfolders (which are now empty)? I.e., eliminate a level in the folder hierarchy?

To be absolutely clear, the deeper subfolder structure should be preserved.

I've run into this a couple of times now, and I was a little disappointed this doesn't seem to be a feature of Dolphin, nor something other people are struggling with.

I suspect this may have to be split in two, moving the contents of the subfolders, and deleting the subfolders. However, this may have the undesired side-effect of deleting empty second-level sub-folders.

Best Answer

Actually not a real one-liner:

find . -mindepth 2 -maxdepth 2 -print -exec mv --backup=numbered -t . '{}' + \
&& find . -mindepth 1 -maxdepth 1 -type d -empty -delete

First find everything in the subfolder with exact depth 2 and move it to .. Then find and delete all empty folders in the current directory.

  • if you have files/folders with the same name they will be renamed with original_filename.~n~ (n meaning 1, 2, 3 ...).
  • Note that will delete all empty subfolders.

Update:

I'm not happy with the solution above. Too many caveats and problems. For example when --backup=numbered renames the parent folder of your folder you want to move ...

mkdir -p test/test
mv test/test . --backup=numbered
mv: cannot move 'test/test' to './test': No such file or directory

Better use a temporary directory to avoid problems. The temp dir should be on the same file system to avoid the need to copy the files.

tmpdir=$(mktemp -d)
find . -mindepth 2 -maxdepth 2 -print -exec mv -b -t $tmpdir '{}' +
find . -mindepth 1 -maxdepth 1 -type d -empty -delete
mv -b $tmpdir/* .
rm $tmpdir