How to extract a specifically named folder from a recursive directory, delete the others?

what about

  find . -type d -name run -exec mv {} /path/to/X \;

where

  • /path/to/X is your destination directory
  • you start from this same place.
  • then use other answer to remove empty directories.

(on a side note there is a --junk-paths option in zip, either when zipping or unzipping)


I would do this in bash, using globstar. As explained in man bash:

globstar
      If set, the pattern ** used in a pathname expansion con‐
      text will match all files and zero or  more  directories
      and  subdirectories.  If the pattern is followed by a /,
      only directories and subdirectories match.

So, to move the directory run to the top level directory x, and then delete the rest, you can do:

shopt -s globstar; mv x/**/run/ x/  && find x/ -type d -empty -delete

The shopt command enables the globstar option. The mv x/**/run/ x/ will move any subdirectories named run (note that this only works if there is only one run directory) to x and the find will delete any empty directories.

You could do the whole thing in the shell with extended globbing, if you like, but I prefer the safety net of find -empty to be sure no non-empty directories are deleted. If you don't care about that, you can use:

shopt -s globstar; shopt -s extglob; mv x/**/run/ x/ && rm -rf x/!(run)

Definitely more verbose, but doing the job in one step:

Assuming you have python installed

#!/usr/bin/env python3
import shutil
import os
import sys

dr = sys.argv[1]

for root, dirs, files in os.walk(dr):
    # find your folder "run"
    for pth in [d for d in dirs if d == sys.argv[2]]:
        # move the folder to the root directory
        shutil.move(os.path.join(root, pth), os.path.join(dr, pth))
        # remove the folder (top of the tree) from the directory
        shutil.rmtree(os.path.join(dr, root.replace(dr, "").split("/")[1]))

How to use

  1. Copy the script into an empty file, save it as get_folder.py
  2. Run it with the root directory (containg your unzipped stuff) and the name of the folder to "lift" as arguments:

    python3 /full/path/to/get_folder.py /full/path/to/folder_containing_unzipped_dir run
    

And it is done:

enter image description here

enter image description here