0

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

2
  • 3
    Why does it have to be a single command? It could be done with two or three easily enough – roaima Jan 1 '20 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 Jan 1 '20 at 22:37
1

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

2
  • 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 Jan 1 '20 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). – Paul_Pedant Jan 1 '20 at 23:06
0

How about

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.