Terminal – How to Move All Files from Subdirectories to Parent Directory

directoryfilesfindmvterminal

I have a directory structure like this:

├── Tom
│   └── c
│       └── 2
│           ├── file.jpg
│           └── text.txt
└── Sam
    ├── 1
    │   └── c
    │       └── music.aac
    ├── E
    │   └── 9
    │       └── pic.jpg
    └── b
        ├── 9
        │   └── sound.aac
        └── d
            └── book.doc

I'd like to move all files from the various subfolders to the main parent folders (Tom, Sam, etc.) with a single command, and then deleting all the empty subfolders.
How can I do that?

Thank you

Best Answer

Not sure why it has to be a one-liner. But here is one possibility. It finds all files in the given directory tree and moves each such file up two directories.

find -type f | while read; do mv "$REPLY" "$(dirname $REPLY)/../../"; done

Please use with care as the command is very tailored to the directory structure you have given and does not account for other cases (e.g. it will move files from all directories and not just in the leaf directories you have shown).

Related Question