Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 复制文件并保留目录结构_Linux_Bash_Find_Copy - Fatal编程技术网

Linux 复制文件并保留目录结构

Linux 复制文件并保留目录结构,linux,bash,find,copy,Linux,Bash,Find,Copy,我要做的是:找到目录src(或其子目录)中的所有文件,并在其名称中包含str,然后将它们复制到dest,保留子目录结构。例如,我有目录dir1,其中包含foo.txt,还有子目录subdir,其中也包含foo.txt。运行脚本(使用str=txt和dest=dir2)后,dir2应计数foo.txt和subdir/foo.txt。到目前为止,我已经提出了以下代码: while read -r line; do cp --parents $line $dest done <<&

我要做的是:找到目录
src
(或其子目录)中的所有文件,并在其名称中包含
str
,然后将它们复制到
dest
,保留子目录结构。例如,我有目录
dir1
,其中包含
foo.txt
,还有子目录
subdir
,其中也包含
foo.txt
。运行脚本(使用
str=txt
dest=dir2
)后,
dir2
应计数
foo.txt
subdir/foo.txt
。到目前为止,我已经提出了以下代码:

while read -r line; do
    cp --parents $line $dest
done <<< "$(find $src -name "*$str*")"
读取-r行时
;做
cp—父项$line$dest

完成IIUC,这可以通过
find-exec
。假设我们有以下目录:

$ tree
.
└── src
    ├── dir1
    │   └── yet_another_file_src
    └── file_src

2 directories, 2 files
我们可以将包含
*src*
的所有文件复制到
/tmp/copy here
,如下所示:

$ find . -type f -name "*src*" -exec sh -c 'echo mkdir -p /tmp/copy-here/$(dirname {})' \; -exec sh -c 'echo cp {} /tmp/copy-here/$(dirname {})' \;
mkdir -p /tmp/copy-here/./src
cp ./src/file_src /tmp/copy-here/./src
mkdir -p /tmp/copy-here/./src/dir1
cp ./src/dir1/yet_another_file_src /tmp/copy-here/./src/dir1
$ find . -type f -name "*src*" -exec sh -c 'mkdir -p /tmp/copy-here/$(dirname {})' \; -exec sh -c 'cp {} /tmp/copy-here/$(dirname {})' \;
$ tree /tmp/copy-here
/tmp/copy-here
└── src
    ├── dir1
    │   └── yet_another_file_src
    └── file_src

2 directories, 2 files
请注意,我使用了
echo
,而不是真正运行此命令- 阅读输出并确保这是您想要的 实现如果你确定这将是你想要的,只需删除
echo
像这样:

$ find . -type f -name "*src*" -exec sh -c 'echo mkdir -p /tmp/copy-here/$(dirname {})' \; -exec sh -c 'echo cp {} /tmp/copy-here/$(dirname {})' \;
mkdir -p /tmp/copy-here/./src
cp ./src/file_src /tmp/copy-here/./src
mkdir -p /tmp/copy-here/./src/dir1
cp ./src/dir1/yet_another_file_src /tmp/copy-here/./src/dir1
$ find . -type f -name "*src*" -exec sh -c 'mkdir -p /tmp/copy-here/$(dirname {})' \; -exec sh -c 'cp {} /tmp/copy-here/$(dirname {})' \;
$ tree /tmp/copy-here
/tmp/copy-here
└── src
    ├── dir1
    │   └── yet_another_file_src
    └── file_src

2 directories, 2 files
编辑: 当然,您可以始终使用
rsync

$ rsync -avz --include "*/"  --include="*src*" --exclude="*" "$PWD"  /tmp/copy-here
您需要
$(cd$src;find.-name“*$str*”)
来避免不需要的子目录级别。“There string from
find
”充其量是可疑的。