The problem I am facing is that I have a directory that contains thousands of subdirectories, each of those subdirectories contain more subdirectories, and inside of all of those are images.

What I have are thousands of these:


I basically want to eliminate the 7624 directory here so that I end up with thousands of these instead:


I tried mv */*/* */* but that just freaked out... is this even possible to do with a terminal command?

I'm trying to do this so I can use this multifile uploader without going into 50 directories just to grab 50 images.

for dir in */*; do
  if [[ -d "$dir" ]]; then
      cd "$dir"
      mv -n * ..
      cd ..
      rmdir "$( basename "$dir" )"

Be aware that any duplicated file or subdirectory names will not be moved and so the deep directories in those cases will not be removed, due to still containing files.

| improve this answer | |
  • So run this from the directory that contains the initial subdirectories? – Octoxan Nov 29 '18 at 16:20
  • Given your example of /1056/7624/image.png, run this from the directory that contains the 1056 directory. – DopeGhoti Nov 29 '18 at 16:21
  • Oddly I get a bunch of rmdir: failed to remove '1103/1560': No such file or directory for every one of them – Octoxan Nov 29 '18 at 16:22
  • It is moving the images up one directory though, just not removing the subdirectories, even though I can verify the ones in the error do exist. – Octoxan Nov 29 '18 at 16:23
  • Fixed, I forgot to trim the outer directory from the rmdir. – DopeGhoti Nov 29 '18 at 16:23

this will move all files from current dir and any sub-dirs, up to the current level. Renaming any files with the same name with a number appended.

find ./ -type f -print -exec mv --backup=numbered {} . \;

then you can make sure you got everything with a

find ./ -mindepth 2 -type f
| improve this answer | |
  • downvotes for literally no reason. i like it. – Wayne Dec 3 '18 at 18:32

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.