为什么 uniq 实用程序给我带来意想不到的结果?

为什么 uniq 实用程序给我带来意想不到的结果?

我正在创建一个 shellscript,它将打印出目录中的各种文件类型。它几乎可以工作,但是,由于某些奇怪的原因,当我尝试在输出上使用 uniq 时,它不起作用。这是我的输入(以及 的值$FILE_TYPE

POSIX shell script, ASCII text executable
ASCII text
Bourne-Again shell script, ASCII text executable
UTF-8 Unicode text, with overstriking
Bourne-Again shell script, ASCII text executable

但是当我使用

FILE_TYPE_COUNT=`echo "$FILE_TYPE" | sort | uniq -c`

这是它打印的结果

  1 POSIX shell script, ASCII text executable
  1 ASCII text
  1 Bourne-Again shell script, ASCII text executable
  1 UTF-8 Unicode text, with overstriking
  1 Bourne-Again shell script, ASCII text executable

显然应该是

  1 POSIX shell script, ASCII text executable
  1 ASCII text
  2 Bourne-Again shell script, ASCII text executable
  1 UTF-8 Unicode text, with overstriking

知道我做错了什么吗?

答案1

在过滤文件之前,您没有对文件进行排序。来自联机帮助页

注意:uniq不检测重复行,除非它们相邻。您可能想首先对输入进行排序,或者使用sort -uwithout uniq。此外,比较遵循 指定的规则LC_COLLATE

您还需要处理全部您想要一次性计算的行数。目前,您一次处理一种文件类型,因此uniq -c正确地告诉您每种文件类型都有一种 — 它一次只能看到一种文件类型。

file * | sort | uniq -c

会更合适(大概有一个更具体的全局变量,甚至是要处理的文件列表)。

相关内容