Ubuntu – How to move all subdirectories to current directory

bashcommand linedirectoryscripts

I'm new to shell script programming. Suppose we have a file hierarchy like this:

/A/B/C/D
/A/B/E/F/G
/A/H/I
/A/H/J/K

Note that here we not only have /A/B/.., but also /A/H/.... All letters are directories. We'd like to transform the hierarchy into:

/A/B/C
/A/B/D
/A/B/E
/A/B/F
/A/B/G
/A/H/I
/A/H/J
/A/H/K

That is, to move all directories at a depth greater than two (dir A has depth zero), to depth two.
I can use JAVA and C to implement it, but they are a bit too slow. Does anyone know how to use a shell script to implement it?

The pseudo-code is as follow:

for each directory D in current directory A // A may have more than one subdirectories
    for each directory d in D
        for each object in d
            if object is a directory
                move object and all descendant subdirectories of object to /A/D;
            end if
        end for
    end for
end for

Best Answer

for dir in /A/*; do
    find "$dir" -mindepth 2 -depth -type d -exec mv -t "$dir" -- {} \;
done

This instructs find to search for all directories (-type d) at least 2 levels underneath (-mindepth 2) $dir depth-first (-depth). For each object it finds it runs mv -t "$dir" -- <SRC>. As always, mv doesn't allow you to merge a source directory into an existing target directory (but there are ways around that).

You can also avoid running an individual instance of mv for each source directory:

[...] -exec mv -t "$dir" -- {} +
Related Question