簡體   English   中英

從所有子目錄中復制具有特定擴展名的所有文件並保留子目錄的結構

[英]Copy all files with a certain extension from all subdirectories and preserving structure of subdirectories

如何在保留原始子目錄結構的同時將特定文件從所有目錄和子目錄復制到新目錄?

這個答案

find . -name \*.xls -exec cp {} newDir \;

解決從同一目錄 newDir 中的所有子目錄復制所有 xls 文件。 那不是我想要的。

如果 xls 文件位於: /s1/s2/ ,則應將其復制到newDir/s1/s2

將所有文件夾和子文件夾中的所有文件復制到新文件夾,但原始文件結構丟失。 一切都被復制到一個新的文件夾中。

你可以試試:

find . -type f -name '*.xls' -exec sh -c \
'd="newDir/${1%/*}"; mkdir -p "$d" && cp "$1" "$d"' sh {} \;

這適用於d="newDir/${1%/*}"; mkdir -p "$d" && cp "$1" "$d" d="newDir/${1%/*}"; mkdir -p "$d" && cp "$1" "$d" shell 腳本到所有xls文件,即先創建目標目錄,將文件復制到目標目錄。

如果您有很多文件和性能問題,您可以嘗試使用以下方法進行一些優化:

find . -type f -name '*.xls' -exec sh -c \
'for f in "$@"; do d="newDir/${f%/*}"; mkdir -p "$d" && cp "$f" "$d"; done' sh {} +

第二個版本分批處理文件,因此生成的 shell 更少。

這應該做:

# Ensure that newDir exists and is empty. Omit this step if you
# don't want it.
[[ -d newDir ]] && rm -r newDir && mkdir newDir

# Copy the xls files.
rsync -a --include='**/*.xls'  --include='*/' --exclude='*' . newDir

這里的技巧是includeexclude的組合。 默認情況下, rsync復制其源目錄下的所有內容( .在您的情況下)。 我們通過排除一切來改變這一點,但也包括xls 文件。

在您的示例中, newDir本身是您工作目錄的子目錄,因此是搜索復制的目錄樹的一部分。 我會重新考慮這個決定。

注意:這不僅會復制名稱以.xls結尾的目錄,還會重新創建源代碼樹的整個目錄結構(即使其中沒有 xls 文件),並僅使用 xls 文件填充它。

感謝您的解決方案。

同時我還發現:

find . -name '*.xls' | cpio -pdm newDir

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM