简体   繁体   English

将目录中的所有文件复制到linux中的本地子目录

[英]Copy all files in a directory to a local subdirectory in linux

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 . 我想在new_subdirnew_subdir此目录中的所有现有文件和目录。 How can I accomplish this via the linux terminal? 我怎样才能通过linux终端实现这一目标?

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 -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. 此代码使用正则表达式查找不是new_subdir的所有文件和目录(在当前目录中)并将它们复制到new_subdir中。 The ! -regex '.' ! -regex '.' ! -regex '.' bit is in there to keep the current directory itself from being included. bit在那里保持当前目录本身不被包含。 Using find is the most powerful technique I know, but it's long-winded and a bit confusing at times. 使用find是我所知道的最强大的技术,但它有时候很冗长,有点令人困惑。

Copy with extglob: 用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 ! 如果您为bash终端启用了extglob(可能就是这种情况),那么您可以使用! to copy all things in the current directory which are not new_subdir into new_subdir. 将当前目录中不是new_subdir的所有内容复制到new_subdir中。

Copy without extglob: 没有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. 如果你没有extglob并且find对你没有吸引力并且你真的想做一些hacky,你可以将所有文件移动到子目录中,然后以递归方式将它们复制回原始目录。 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. 与将目标文件夹复制到自身的cp不同,mv在尝试移动目标文件夹本身时会抛出错误。 (But it successfully moves every other file and folder.) (但它成功移动了所有其他文件和文件夹。)

You mean like 你的意思是

cp -R * new_subdir

?

cp take -R as argument which means recursive (so, copy also directories), * means all files (and directories). cp-R作为参数,这意味着递归(因此,复制也是目录), *表示所有文件(和目录)。

Although * includes new_subdir itself, but cp detects this case and ignores new_subdir (so it doesn't copy it into itself!) 虽然*包含new_subdir本身,但是cp检测到这种情况并忽略new_subdir (因此它不会将其复制到自身!)

尝试类似的东西:

 cp -R * /path_to_new_dir/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM