如何在Linux系統上遞迴搜尋和刪除目錄?
刪除目錄是任何在Unix系統上工作的人都經常進行的操作。但有時我們也需要先找到目錄,然後決定是否刪除它。刪除檔案的一個障礙是進行遞迴刪除,因為預設情況下,如果目錄非空,Unix系統不允許刪除目錄。因此,在本文中,我們將瞭解如何查詢和遞迴刪除目錄。
使用find和exec
下面的命令首先使用find命令搜尋所需的目錄,然後使用遞迴選項和強制選項執行‘rm’命令來遞迴刪除目錄。命令中使用的各種引數在該命令下方解釋。
$find /path/to/search -name " Dir name to be deleted " -type d -exec /bin/rm -rf {} +這些引數的含義如下。
-type d - restricts the search only to directories
-exec - executes an external command, in this case it is rm –r
{} + - appends the found files to the end of the rm command使用find和xargs
xargs允許像rm和mkdir這樣的命令接受標準輸入作為引數。因此,在這種情況下,我們首先使用find命令查詢所需的目錄,然後透過將其作為引數提供給xargs命令來對該目錄進行操作。print0選項允許使用完整的目錄路徑,該路徑將提供給xrags命令。然後,我們以與上面exec命令類似的方式應用rm命令。
$find /path/to/search -name " Dir name to be deleted " -type d -print0 | xargs -0 /bin/rm -rf "{}"
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP