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

  • 3
    Why does it have to be a single command? It could be done with two or three easily enough Commented Jan 1, 2020 at 21:03
  • 1
    My bad, does not have to be a single command, what I wanted to say was without doing it once per folder.
    – linkxvi
    Commented Jan 1, 2020 at 22:37

2 Answers 2


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).

  • If you put in there another while ... indirection, it would work for arbitrary nested sub folders (well the command will be abit more complicated, but I guess you get the idea) ;)
    – jerch
    Commented Jan 1, 2020 at 22:09
  • A similar command with find -depth -d would then find all subdirectories. -exec rmdir on those would be relatively safe because rmdir will only remove empty directories (unlike rm -r). Commented Jan 1, 2020 at 23:06

How about

find Tom Sam -type f | while read FN; do echo mv "$FN" "${FN%%/*}"; done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .