如何计算 find 命令返回的文件数?

how to count number of files that find command has returned?

这里我得到的结果是 1 而不是应该找到的两个文件:

mkdir -p mytestdir001
mkdir -p mytestdir002
LIST=`find -maxdepth 1 -name "mytestdir???"`
echo ${#LIST[@]}

你为什么不使用:

find -maxdepth 1 -name "mytestdir???" | wc

如果你的真正目标是知道这个数字?

你可以使用 wordcount ( wc ) :

find -maxdepth 1 -name "mytestdir???" | wc

这会给你这样的输出:

2       2      30

这些是:

  • 行数
  • 字数
  • 字符数

使用 wc -l 仅获取行数。

使 LIST 成为数组而不是变量:

LIST=( `find -maxdepth 1 -name "mytestdir???"` )

也开始使用 $() 而不是旧的 ``:

LIST=( $(find -maxdepth 1 -name "mytestdir???") )

您可以将 find 的输出通过管道传输到 wc 并计算行数,因为每个文件都由不同的行表示 - 根据我的经验,find 就是这种情况。

http://linux.die.net/man/1/wc

例子

[user@machine find]# find . -name "*.file"

./3.file

./1.file

./2.file

[user@machine find]# find . -name "*.file" | wc -l

3

ls | awk '/^mytestdir/{a++}END{print a}' # 2

细分:

ls | awk '
  # Match every folder / file starting with mytestdir
  /^mytestdir/{a++}
  # Print counted matches
  END{print a}' # 2