Skip to content

Instantly share code, notes, and snippets.

@m41039
Last active September 20, 2017 07:02
Show Gist options
  • Save m41039/06bcdd4d6a7168d19007c455d7758945 to your computer and use it in GitHub Desktop.
Save m41039/06bcdd4d6a7168d19007c455d7758945 to your computer and use it in GitHub Desktop.
Bash_shell_script列出目錄及檔案數量
原文出處 http://benjr.tw/66816
ls 指令只能很簡單的看目前所有檔案,一些要列出 該目錄下 所有目錄及檔案數量 的顯示方式都沒有辦法,須要透過標準表示式才能完成,這些指令是在網路上找到的.
顯示檔案數目:
#ls -laR |grep "^-" |awk 'END{print "Number of files:"NR}'
顯示目錄數目:
#ls -laR |grep "^d" |awk 'END{print "Number of directories:"NR}'
來看看他是怎麼使用這些指令集合的,主要是 ls + grep + awk
#ls -laR
-l : 列出詳細資料
-a : 顯示所以檔案和目錄,包含 . 開頭的隱藏檔案
-R : recursive 一併顯示子目錄的目錄檔案
grep “^-“
“^” : 指匹配的字符串在行首
“^-” : 找出 – (- 表示為檔案,d 表示為目錄)的字符串在行首
awk ‘END{print “Number of files:”NR}’
awk ‘條件類型1{動作1} 條件類型2{動作2} …’ filename
條件類型是 END , 動作 是 print
print 的功能是將欄位資料列出來
單純顯示出 “Number of files:”(只顯示””內的字串,不包含””)
NR 表示 awk 所處理的資料是到 “第幾行” 了
filename 沒有指定是因為我們用了 | (pipeline) ,所以前面 #ls -laR |grep “^-” 處理完的資料會交由 awk 繼續處理.
[root@benjr ~]# pwd
/root
[root@benjr ~]# ls -laR |grep "^-" |awk 'END{print "Number of files."NR}'
Number of files.2512
[root@benjr ~]# ls -laR |grep "^d" |awk 'END{print "Number of directories."NR}'
Number of directories.3752
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment