在 UNIX 中循環列出檔案

在 UNIX 中循環列出檔案

我已經發出命令:

ls -lrt

列出的文件和目錄是:

drwxr-xr-x   4 root root    4096 Feb  2  2014 abc
drwxr-xr-x   4 root root    4096 Feb  2  2014 cde
drwxr-xr-x   4 root root    4096 Feb  2  2014 efg
-rwxr-xr-x   4 root root    4096 Feb  2  2014 aaa.txt

現在我想透過使用 for 迴圈或 while 迴圈來尋找列出的輸出檔是否是目錄。

答案1

對於ls,使用以下命令僅列出目錄。

ls -d -- */

要使用 ls 本身列出常規檔案(並假設檔案名稱不包含換行符),您可以使用以下命令。

ls -p | grep -v /

要僅列出常規文件,使用 GNU 和其他一些查找實現,您可以使用

find . -maxdepth 1 -type f

(請注意,與前一個相反,它還包括隱藏文件並且列表未排序)

標準等效項是:

find . ! -name . -prune -type f

答案2

如果您想要一個類似「shell 腳本範本」的東西來了解如何循環目錄內容並根據檔案類型執行操作,以下內容可能會給您提示:

for f in *
do
   if [[ -d "$f" ]]
   then
      ... your processing of directories here, reference them as "$f" ...
   fi
done

這將查看當前目錄中的所有條目,檢查它們是否是目錄,並對它們執行您喜歡的任何處理。請注意,目錄測驗的語法是 BASH 特定的;對於一般情況,使用if [ -d "$f" ].

另一種方法將清單限制為僅目錄條目:

for d in */
do
    ... whatever you need to do on directory "$d" ...
done

答案3

您不需要循環來尋找所有目錄,您可以使用以下find命令:

find . -maxdepth 1 -type d

這將列出目前目錄中的所有目錄。如果你想要ls -l輸出,你可以這樣做:

find . -maxdepth 1 -type d | xargs ls -ld

如果您確實想使用循環,可以使用以下構造:

for file in $(ls)
do
  if [[ -d $file ]]
  then
    ls -ld $file
  fi
done

for循環遍歷 所傳回的所有條目ls,然後if測試該條目是否為目錄。

答案4

列出目錄名稱

compgen -d

不是從一個點開始

compgen -d -X '.*' | xargs ls -dlrt

相關內容