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


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:


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
for dir in /A/*; do
    find "$dir" -mindepth 2 -depth -type d -exec mv -t "$dir" -- {} \;

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" -- {} +
  • Thanks for your answer. However, A may originally have many subdirectories, then this will be "find /A/B1 ...", "find /A/B2 ...", etc. Is there any way to consider all subdirectories under A? – user3813057 Mar 18 '15 at 2:01
  • I'll address this in an edit to my answer. Please update your question to clarify it according to your comment. – David Foerster Mar 18 '15 at 2:04
  • Hi I met this problem: mv: cannot move ./A/B/C/D/E' to ./A/B/E': Directory not empty is there anything wrong? – user3813057 Mar 18 '15 at 2:22
  • This happens, because ./A/B/E, the destination, is a non-empty directory. As I explained in my answer, mv doesn't merge directories. Do you want to merge the content of directories of the same name? – David Foerster Mar 18 '15 at 2:43

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.