How to move subdirectories into another subdirectory within the same directory?

There is a directory dir/. It contains subdirectories az. I need to move subdirectories ay into subdirectory z.
If that’s hard, then not az, but by providing a list of directories that need to be moved.

How can I do this in bash?

Asked By: alxprogger


Use brace expansion :

For your case, do:

mv {a..y} z/

If you have list of directories, say dir1, dir2, and dir3, then do something like:

mv -t z/ dir1 dir2 dir3

Or maybe:

mv -t z/ dir{1..3}

Brief Explanations:

  • -t option means "target". It is usually used to avoid confusion in cases involving movement of multiple files/directories.
  • Brace expansion work in the way that {1..15} will print all the numbers from 1 till 15, and {a..f} will print all alphabets from a till f.
Answered By: shivams

As for me more secure way to use find

find dir/* -prune -type d -name "[a-y]" ! -name "z" -exec mv -t dir/z {} +
Answered By: Costas

Note: this is not the cleanest way to do it (see shivams’ answer for that), and just works if you only have the directories a-z inside dir.

I’ve always used the easier to remember

mv * z

which, of course, complains that

mv: cannot move ā€˜zā€™ to a subdirectory of itself, ā€˜z/zā€™

but otherwise does what you want.

This applies (at least) to GNU coreutils

Answered By: loopbackbee
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.