[英]How can I recursively copy same-named files from one directory structure to another in bash?
我有兩個目錄,比如dir1
和dir2
,它們具有完全相同的目錄結構。 如何以遞歸方式將所有*.txt
文件從dir1
復制到dir2
?
例:
我要復制
dir1/subdir1/file.txt
dir1/subdir2/someFile.txt
dir1/.../..../anotherFile.txt
至
dir2/subdir1/file.txt
dir2/subdir2/someFile.txt
dir2/.../..../anotherFile.txt
最后一個文件示例中的.../...
表示這可以是任何子目錄,它本身可以有子目錄。
我想再次以編程方式執行此操作。 這是偽代碼
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
您可以簡單地使用rsync
。 這個答案來自這個主題 。
rsync -av --include='*.txt' --include='*/' --exclude='*' dir1/ dir2/
如果您在dir1中只有.txt
文件,這將起作用:
cp -R dir1/* dir2/
但是,如果您有其他文件擴展名,它也會復制它們。 在這種情況下,這將工作:
cd /path/to/dir1
cp --parents `find . -name '*.txt'` path/to/dir2/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.