8

I have a directory with the following structure:

file_1
file_2
dir_1
dir_2
# etc.
new_subdir

I'd like to make a copy of all the existing files and directories located in this directory in new_subdir. How can I accomplish this via the linux terminal?

1
  • You're not moving, you're copying Commented Dec 16, 2014 at 17:51

3 Answers 3

7

This is an old question, but none of the answers seem to work (they cause the destination folder to be copied recursively into itself), so I figured I'd offer up some working examples:

Copy via find -exec:

find . ! -regex '.*/new_subdir' ! -regex '.' -exec cp -r '{}' new_subdir \;

This code uses regex to find all files and directories (in the current directory) which are not new_subdir and copies them into new_subdir. The ! -regex '.' bit is in there to keep the current directory itself from being included. Using find is the most powerful technique I know, but it's long-winded and a bit confusing at times.

Copy with extglob:

cp -r !(new_subdir) new_subdir

If you have extglob enabled for your bash terminal (which is probably the case), then you can use ! to copy all things in the current directory which are not new_subdir into new_subdir.

Copy without extglob:

mv * new_subdir ; cp -r new_subdir/* .

If you don't have extglob and find doesn't appeal to you and you really want to do something hacky, you can move all of the files into the subdirectory, then recursively copy them back to the original directory. Unlike cp which copies the destination folder into itself, mv just throws an error when it tries to move the destination folder inside of itself. (But it successfully moves every other file and folder.)

Sign up to request clarification or add additional context in comments.

Comments

4

You mean like

cp -R * new_subdir

?

cp take -R as argument which means recursive (so, copy also directories), * means all files (and directories).

Although * includes new_subdir itself, but cp detects this case and ignores new_subdir (so it doesn't copy it into itself!)

2 Comments

You may also want to see this if you want to make sure new_subdir is excluded from * and no warning is generated
In macOS this will loop
0

Try something like:

 cp -R * /path_to_new_dir/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.