2015-11-02 22 views
1

我試圖刪除隱藏的所有目錄和文件,並遞歸刪除它們。當前目錄級別的唯一隱藏目錄是...,但幾個目錄中的每個目錄都有幾個隱藏文件(以._開頭)。 ls -aR | egrep '^\.\w+' |會列出我想要的所有文件,但添加'| xargs'rm'給我rm錯誤「沒有這樣的文件或目錄」。用egrep和xargs刪除嵌套隱藏文件

我認爲這意味着我試圖刪除的每個目錄需要附加它的父目錄和/。但也許我錯了。

如何更新此命令以刪除這些文件?

回答

5

使用find

find . -type f -name .\* -exec rm -rf {} \; 

-exec是白色空間安全:{}將傳遞文件的路徑(相對於.)作爲一個參數來rm

更好的是這樣的:

find . -name .\* -delete 

(與感謝@ John1024)。第一種形式爲每個找到的文件生成一個進程,而第二種形式不生成。

xargs默認情況下是沒有空格安全:

$ touch a\ b 
$ find . -maxdepth 1 -name a\ \* | xargs rm 
rm: cannot remove ‘./a’: No such file or directory 
rm: cannot remove ‘b’: No such file or directory 

這是因爲它分裂它在空格輸入提取文件名。我們可以使用另一個分隔符;從man find

-print0 
      True; print the full file name on the standard output, followed 
      by a null character (instead of the newline character that 
      -print uses). This allows file names that contain newlines or 
      other types of white space to be correctly interpreted by pro‐ 
      grams that process the find output. This option corresponds to 
      the -0 option of xargs. 

所以:

find . -type f -name .\* -print0 | xargs -0 rm 
+0

甚至'-exec RM -rf {} \;' – fedorqui

+0

@fedorqui是這就是我想要的使用太;-) – Kenney

+0

謝謝。即在當前目錄中查找隱藏的目錄,但不在可見目錄中隱藏文件。 – 1252748