Search code examples
shellfileterminaldirectorysubdirectory

Recursively flattening subdirectories in a root directory and maintaining level 1 sub-directory structure


I have a large n-level directory structured as follows:

root
  |
   subdir1
      |
       sub_subdir1
           |
            ....(n-2 levels).....
                                 |
                                  file1
  |
   subdir2
      |
       sub_subdir2
           |
            ....(n-2 levels).....
                                 |
                                  file2

I want to flatten the directory so that all level 1 subdirs contain files. I also want to remove the level 2 to (n-1) sub_subdirs as they contain no files.

Desired Result

root
  |
   subdir1
      |
       file1
  |
   subdir2
      |
       file2

I have found a lot of posts explaining methods to flatten directories but none that explains how to do this in a controlled manner, i.e.,

  • by specifying the levels to be flattened
  • or doing it recursively for all sub_directories in a root directory

Solution

  • I posted the same on stackexchange Unix & Linux and got two comprehensive solutions. Here is the link - https://unix.stackexchange.com/questions/531929/recursively-flattening-subdirectories-in-a-root-directory-and-maintaining-level/531937?noredirect=1#comment984926_531937