GNU find 刪除目錄中的檔案但保留目錄本身

GNU find 刪除目錄中的檔案但保留目錄本身

我花了一個下午的大部分時間試圖解決這個問題。

答案1

若要刪除目前目錄下並命名的任何目錄中的所有文件,node_modules同時保留node_modules

find . -path  '*/node_modules/*' -delete

(這是用 GNU 測試的,find但我預期 BSD/OSXfind也會有類似的行為。)

例子

讓我們建立一個node_modules目錄,其中包含一些檔案:

$ mkdir -p node_modules/dir{1..3}
$ touch node_modules/file{1..3}

現在,讓我們看看該find命令返回哪些文件:

$ find . -path  '*/node_modules/*'
./node_modules/dir3
./node_modules/dir1
./node_modules/file3
./node_modules/file2
./node_modules/file1
./node_modules/dir2

這顯示了文件裡面 node_modules不是目錄node_modules本身。因此,我們可以使用以下命令刪除檔案:

$ find . -path  '*/node_modules/*' -delete
$ ls
node_modules

相關內容