[英]How to copy all files from a directory and its subdirectories to another dir?
I have a /dir1
, the structure is:我有一个
/dir1
,结构是:
./aaa.txt
./bbb.jpg
./subdir1/cccc.doc
./subdir1/eeee.txt
./subdir2/dddd.xls
./subdir2/ffff.jpg
I want to copy all .txt
and .jpg
in /dir1
and its subdirectories to /dir2
.我想将
/dir1
及其子目录中的所有.txt
和.jpg
复制到/dir2
。
By using cp -r /dir1/* /dir2
, it copies all files and its structure to /dir2
.通过使用
cp -r /dir1/* /dir2
,它将所有文件及其结构复制到/dir2
。
By using cp -r /dir1/*.jpg /dir2
and cp -r /dir1/*.txt /dir2
, it doesn't copy the .jpg
and .txt
files in the subdirectories.通过使用
cp -r /dir1/*.jpg /dir2
和cp -r /dir1/*.txt /dir2
,它不会复制子目录中的.jpg
和.txt
文件。
By using通过使用
for FILE in `find`
do
cp -f $FILE /dir1/
done
it can copy all files in dir and subdirectories to the destination, but I cannot filter the file type.它可以将 dir 和子目录中的所有文件复制到目标,但我无法过滤文件类型。
Is there another way that can achieve what I want?有没有另一种方法可以实现我想要的?
You can use find
to get the desired source files, and then use cp
within the -exec
predicate of find
to copy the files to the desired destination.您可以使用
find
来获取所需的源文件,然后在find
的-exec
谓词中使用cp
将文件复制到所需的目的地。 With GNU cp
:使用 GNU
cp
:
find /dir1/ -type f \( -name '*.txt' -o -name '*.jpg' \) -exec cp -t /dir2/ {} +
POSIX-ly: POSIX-ly:
find /dir1/ -type f \( -name '*.txt' -o -name '*.jpg' \) -exec cp {} /dir2/ \;
With the globstar
1 and extglob
shell options:使用
globstar
1和extglob
shell 选项:
shopt -s globstar extglob
cp dir1/**/*.@(txt|jpg) dir2
The **/
expression matches zero or more directories or subdirectories, so you get files from the whole subtree of dir1
; **/
表达式匹配零个或多个目录或子目录,因此您可以从dir1
的整个子树中获取文件; @(txt|jpg)
is an extended pattern that matches either txt
or jpg
. @(txt|jpg)
是匹配txt
或jpg
的扩展模式。
For the somewhat unlikely case that there are no .jpg
and .txt
files in any of dir1
, but a file called *.@(txt|jpg)
in a subdirectory of dir1
called **
, you may also want to set the failglob
shell option so the command is not executed if the glob doesn't match anything – instead of copying the unlikely file.对于在
dir1
任何一个中没有.jpg
和.txt
文件,但在dir1
名为**
的子目录中有一个名为*.@(txt|jpg)
的文件的不太可能的情况,您可能还需要设置failglob
shell选项,因此如果 glob 不匹配任何内容,则不会执行该命令 - 而不是复制不太可能的文件。
1 globstar
was added in Bash 4.0 and is thus not available for the Bash that comes standard with Mac OS (3.2). 1
globstar
是在 Bash 4.0 中添加的,因此不适用于 Mac OS (3.2) 标配的 Bash。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.