计算目录中文件数的脚本

use*_*477 6 find shell-script files

我正在寻找一个脚本来计算当前目录(不包括子目录)中的文件。它应该遍历每个文件,如果不是目录,则增加一个计数。输出应该只是一个表示文件数的整数。

我想出了

find . -type f | wc -l
Run Code Online (Sandbox Code Playgroud)

但我真的不认为它完成了整个计数。这是一个任务,所以如果你只想给我指出正确的方向,那就太好了。

Sté*_*las 10

如果你只想要普通文件,

使用 GNU find

find . -maxdepth 1 -type f -printf . | wc -c
Run Code Online (Sandbox Code Playgroud)

其他find

find . ! -name . -prune -type f -print | grep -c /
Run Code Online (Sandbox Code Playgroud)

(您不想要-print | wc -l,因为如果文件名带有换行符,那将不起作用)。

zsh

files=(*(ND.)); echo $#files
Run Code Online (Sandbox Code Playgroud)

ls

ls -Anq | grep -c '^-'
Run Code Online (Sandbox Code Playgroud)

要包含符号链接到正规文件,更改-type f-xtype f与GNU find,或-exec test -f {} \;与其他findS,或.-.zsh,或添加-L选项ls。但是请注意,在无法确定符号链接的目标类型的情况下(例如,因为它位于您无权访问的目录中),您可能会得到漏报

如果您想要任何类型的文件(符号链接、目录、管道、设备...),不仅仅是常规文件:

find . ! -name . -prune -printf . | wc -c
Run Code Online (Sandbox Code Playgroud)

(变化到-print | grep -c /与非GNU find(ND.)(ND)zshgrep -c '^-'wc -lls)。

这将然而,不能指望...(通常,一个并不真正关心这些,因为他们总是在那里),除非您更换-A-als

如果您想要除目录之外的所有类型的文件,请替换-type f! -type d(或! -xtype d同时排除指向目录的符号链接)和 with zsh、替换.^/和 with ls、替换grep -c '^-'grep -vc '^d'

如果要排除隐藏文件,请添加! -name '.*'或 with zsh,删除D或 with ls,删除A.


thi*_*ael -3

您的命令将包含子目录。

我会选择:

count=0
for file in $(ls -a); do 
  if [ -f $file ]; then 
    count=$(expr $count + 1)
  fi
done
echo "There are $count files on $(pwd)"
Run Code Online (Sandbox Code Playgroud)

  • 请参阅http://unix.stackexchange.com/questions/128985/why-not-parse-ls (2认同)