6

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?

cdrini
  • 989
  • 10
  • 17
GSto
  • 41,512
  • 37
  • 133
  • 184

3 Answers3

5

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.)

Community
  • 1
  • 1
Eihiko
  • 59
  • 1
  • 3
3

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!)

Shahbaz
  • 46,337
  • 19
  • 116
  • 182
1

Try something like:

 cp -R * /path_to_new_dir/
Bogdan Emil Mariesan
  • 5,529
  • 2
  • 33
  • 57