0

I have a directory named temp. Inside this folder, I have multiple sub-folders ( I don't know the exact number ). Now I create another sub-folder inside temp named Untitled. Now I want to move all the other sub-folders inside Untitled.

Let's say I have 3 folders inside temp named a,b,c. Now I create Untitled. So temp now contains 4 folders a,b,c and Untitled. After performing the operation temp will contain only the Untitled folder with Untitled containing a,b,c.

How can I achieve this using bash?

My Bash version ( on Ubuntu 16.04 )

GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)
1

Assuming you have only the folders inside the main folder, the most simple way is this from temp (first cd to temp):

mv * Untitled

You'll get one error, saying:

mv: cannot move 'Untitled' to a subdirectory of itself, 'Untitled/Untitled'

If this is a problem for you, you can use a loop over * and moving each file one by one, skipping the target subfolder.

$ mkdir a b c
$ target_dir=Untitled
$ mkdir "$target_dir"
$ for f in *; do
if [ "$target_dir" == "$f" ]; then continue; fi; mv "$f" "$target_dir"; done
$ ls
Untitled
$ ls Untitled/
a  b  c

If there are files you want to skip, add the condition inside the loop before the mv command.

  • 1
    Use a pattern like ./* to avoid issues with filenames that start with a dash and look like options. – ilkkachu Nov 11 '18 at 20:41
3

Briefly, and without errors, you could use bash's extended globbing to exclude the one directory that you want to omit:

shopt -s extglob
mv -- !(Untitled) Untitled

After ensuring that extended globbing is turned on, the mv command works by expanding the first parameter (!(Untitled)) into every file and directory in the current directory except for the one named "Untitled". All of those files and directories are then moved into the Untitled directory.

If you only want to move directories from the current directory into Untitled, then add one character:

shopt -s extglob
mv -- !(Untitled)/ Untitled

... where the trailing / forces bash to match a directory instead of a file.

The above will omit dot-files by default (such as .subdir). If you want to pick those up as well, simply add:

shopt -s dotglob

For more on those shell options, see:

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.