获取文件中的最小行(基于字符串字典顺序的最小行)

Get smallest line in a file (smallest based on string lexicographic order)

给定一个包含以下内容的文件:

2011-03-01
2011-04-01
2011-01-01
2011-05-01
2011-02-01

我想得到:

2011-01-01

如果我们根据字典顺序比较行,这是文件中最小的行。

实现此目的的一种方法是先对行进行排序,然后 return 第一行:

sort file | head -n 1

然而,由于 sort,这具有 O(n logn) 的复杂性,而最小操作应该是仅需 O(n) 即可实现,其中 n 是行数。

有人知道更聪明 and/or 更有效的方法吗?

您可以尝试 awk 'NR==1 || [=10=] < min {min=[=10=]} END {print min}' file,计时,看看它是否比 sort|head