[英]How can I recursively copy same-named files from one directory structure to another in bash?
I have two directories, say dir1
and dir2
, that have exactly the same directory structure. 我有两个目录,比如
dir1
和dir2
,它们具有完全相同的目录结构。 How do I recursively copy all the *.txt
files from dir1
to dir2
? 如何以递归方式将所有
*.txt
文件从dir1
复制到dir2
?
Example: 例:
I want to copy from 我要复制
dir1/subdir1/file.txt
dir1/subdir2/someFile.txt
dir1/.../..../anotherFile.txt
to 至
dir2/subdir1/file.txt
dir2/subdir2/someFile.txt
dir2/.../..../anotherFile.txt
The .../...
in the last file example means this could be any sub-directory, which can have sub-directories itself. 最后一个文件示例中的
.../...
表示这可以是任何子目录,它本身可以有子目录。
Again I want to do this programmatically. 我想再次以编程方式执行此操作。 Here's the pseudo-code
这是伪代码
SRC=dir1
DST=dir2
for f in `find ./$SRC "*.txt"`; do
# $f should now be dir1/subdir1/file.txt
# I want to copy it to dir2/subdir1/file.txt
# the next line coveys the idea, but does not work
# I'm attempting to substitute "dir1" with "dir2" in $f,
# and store the new path in tmp.txt
echo `sed -i "s/$SRC/$DST/" $f` > tmp.txt
# Do the copy
cp -f $f `cat tmp.txt`
done
If you only have .txt
files in dir1, this would work: 如果您在dir1中只有
.txt
文件,这将起作用:
cp -R dir1/* dir2/
But if you have other file extensions, it will copy them too. 但是,如果您有其他文件扩展名,它也会复制它们。 In this case, this will work:
在这种情况下,这将工作:
cd /path/to/dir1
cp --parents `find . -name '*.txt'` path/to/dir2/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.