在 Linux 上覆制目錄結構而不復制檔案
Linux 中有多個命令可以將目錄從一個位置複製到另一個位置。在 Linux 中,您可以使用帶有 -R 選項的 cp 命令遞迴複製目錄,該命令會將源目錄(包括其所有檔案)複製到目標位置。相反,有時我們只需要將空目錄結構複製到不同的目標目錄,而無需複製源目錄中的檔案。
如果您逐個複製目錄結構而不復制檔案,則需要很長時間。在這種情況下,您可以使用 Linux 中的一些命令直接複製空目錄結構而不復制檔案。本教程將展示所有可用命令的示例,這些命令用於在 Linux 上覆制目錄結構而不復制檔案。
在 Linux 上覆制目錄結構而不復制檔案
在 Linux 中,您可以藉助多個命令複製任何現有的目錄結構和子目錄。在這裡,我們將複製“Documents”目錄結構到“Downloads”目錄,但不包括其檔案。讓我們使用以下 tree 命令考慮“Documents”目錄的結構:
~$: tree -a Documents Documents |__ dir1 | |__sample1.txt |__ dir2 | |__ dir3 | |__ example.txt |__ sample2 |__ sample3 3 directories, 4 files
以上輸出顯示“Documents”目錄有 3 個子目錄和 4 個檔案。現在,我們將僅將這 3 個目錄複製到另一個位置,而不復制任何檔案。在這種情況下,我們可以使用三個命令:
rsync 命令
rsync 是一個強大的命令,用於將檔案從源複製到目標。您可以使用此實用程式複製目錄結構。
~$: rsync -av -f"+ */" -f"- *" " <source> <destination>"
在以上命令中,我們使用:
-a − 用於存檔複製。
-v − 檢視 rsync 命令的詳細日誌。
-f − 每個“f”定義一個過濾器,過濾規則遵循該過濾器。
+ − 包含所有目錄。
- − 排除所有檔案。
例如,讓我們將“Documents”的所有目錄複製到“Downloads”目錄:
~$: rsync -av -f"+ */" -f"- *" " /home/prateek/Documents Downloads" sending incremental file list Documents/ Documents/dir1/ Documents/dir2/ sent 142 bytes received 28 bytes 340.00 bytes/sec total size is 0 speedup is 0.00
如果您使用的是舊版本的 rsync,則可以使用以下命令:
~$: rsync -av --include='*/' --exclude='*' /home/prateek/Documents Downloads
因此,您的源目錄結構將被複制到目標目錄,但不包括檔案。
find 命令
您可以使用 find 命令與 xargs 命令/-exec 選項將完整目錄路徑複製到另一個目標位置。首先,顯示您要複製的目錄結構:
~$: find Documents -type d Documents Documents/dir2 Documents/dir2/dir3 Documents/dir1
要複製目錄結構而不復制檔案,您必須將上述命令與 xargs 命令一起使用,如下所示:
~$: find Documents -type d | xargs -I{} mkdir -p "$HOME/Downloads/{}"
或者,您可以使用 find 命令的 -exec 引數複製目錄結構而不復制檔案,並獲得相同的結果。
~$: find Documents -type d -exec mkdir -p "$HOME/Downloads/{}" \;
這裡我們使用 -type d 選項僅檢索目錄。
tree 和 xargs 命令
在 Linux 中,您可以使用 tree 命令以樹狀格式列出目錄的內容。向此命令新增標誌允許您顯示目錄路徑作為輸出,而無需擴充套件其檔案。
~$: tree -dfi --noreport Documents Documents Documents/dir1 Documents/dir2 Documents/dir2/dir3
在以上命令中:
-d − 僅列印目錄。
-f − 列印完整路徑。
-i − 以樹狀格式顯示輸出。
-noreport − 抑制輸出末尾的摘要報告
現在,讓我們將上述命令管道傳輸到 xargs 命令。它要麼從先前執行的命令或系統使用者獲取標準輸入以執行和構建命令列:
~$: tree -dfi --noreport dir1 | xargs -I{} mkdir -p "$HOME/Downloads/{}"
這裡我們使用 mkdir -p 命令將檢索到的目錄路徑重建到新的目錄路徑。
驗證複製的目錄結構
您可以使用上述任何方法複製目錄結構而不復制檔案,並使用以下 tree 命令進行驗證:
~$: tree -dfi --noreport dir1 | xargs -I{} mkdir -p "$HOME/Downloads/{}" ~$: tree -a $HOME/Downloads/Documents /home/prateek/Downloads/Documents |__dir1 |__dir2 |__dir3 3 directories, 0 files
如您所見,系統已將三個目錄(無檔案,零檔案)複製到新位置。
結論
在本文中,我們解釋了三個在 Linux 上覆制目錄結構而不復制檔案的命令。我們還使用一些示例來解釋 rsync、find 和 xargs 命令。複製目錄非常簡單,您可以使用上述任何方法在 Linux 上覆制目錄結構而不復制檔案。