搜尋所有有 0 個檔案的子目錄

搜尋所有有 0 個檔案的子目錄

我想列印包含零個檔案的所有子目錄的名稱(它們可能包含子目錄)。以下內容適用於目前目錄:

$ ls -p | grep -v / | wc -l | \
  xargs -I % test % -eq 0 && pwd

我認為可能有一個更優雅的解決方案,有什麼建議嗎?我該如何將其更改為遞歸所有子目錄?

我有一個測試結構:test/test1/test4 和 test/test2/test3/test5。唯一的檔案位於 test/test1 中。我想在基礎目錄(test/)中運行該命令。結果應該是: test/ ;測試/測試2/; test/test2/test3/ 因為這些目錄只包含子目錄但沒有檔案。其他可接受的是空端點 test/test1/test4/ 和 test/test2/test3/test5。

答案1

使用 fgrep 過濾掉包含檔案的目錄:

$ find -type d | \
  grep -xFv -f <(find -type f -printf %h\\n)

答案2

像這樣的事情:

find . -type d -exec bash -c 'files=$(find $1 -mindepth 1 -maxdepth 1 -type f | wc -l) ; [[ $files -ne 0 ]] && exit 1 ; exit 0' script {} \; -print

bash -c ...只是一個“小”腳本,在檢查目錄中的檔案後返回 0 或 1。

答案3

解決問題的不同方法:

# Enable advanced glob
shopt -s globstar
# Enable matching hidden files (.*)
shopt -s dotglob
for d in **/; do
   nofiles=true
   for f in "$d"/*; do
     [ -f "$f" ] && nofiles=false && break
   done
   [ $nofiles = true ] && echo "$d"
done
shopt -u globstar
shopt -u dotglob

循環遍歷所有資料夾,在其中循環所有項目並檢查文件。

不是最短的腳本,但不會因檔案名稱中的換行符、空格或類似內容而失敗。 5年後再次看它時,它也很容易閱讀;-)

相關內容