Bash 排序命令数字排序、字段和字典排序

Bash 排序命令数字排序、字段和字典排序

你能解释sort +0nr -2 +2d一下吗?这个例子来自https://www.grymoire.com/Unix/Awk.html评论说:

# numeric sort - biggest numbers first
# sort fields 0 and 1 first (sort starts with 0)
# followed by dictionary sort on fields 2 + 3

请解释所使用的每个论点。

谢谢!

答案1

这是用于指定字段和列值的过时的(或至少是过时的)“传统”语法,记录在info sort

   On systems not conforming to POSIX 1003.1-2001, ‘sort’ supports a
traditional origin-zero syntax ‘+POS1 [-POS2]’ for specifying sort keys.
The traditional command ‘sort +A.X -B.Y’ is equivalent to ‘sort -k
A+1.X+1,B’ if Y is ‘0’ or absent, otherwise it is equivalent to ‘sort -k
A+1.X+1,B+1.Y’.

在您引用的例子中:

sort +0nr -2 +2d

有两组说明符:“ +0 -2”和“ -2”。第一组没有A=0B=2Y,因此相当于现代基于 1 的索引中的 。第二组没有-k0+1,2和,因此变为。-k1,2A=2BY-k3

字母选项具有其通常含义,即

   -d, --dictionary-order
          consider only blanks and alphanumeric characters

   -n, --numeric-sort
          compare according to string numerical value

   -r, --reverse
          reverse the result of comparisons

因此结果是对前两个字段进行反向数字排序,-k1,2nr然后对第三个(及后续)字段进行字典排序-k3d

info页面建议不要使用这种形式的语法:

   Scripts intended for use on standard hosts should avoid traditional
syntax and should use ‘-k’ instead.  For example, avoid ‘sort +2’, since
it might be interpreted as either ‘sort ./+2’ or ‘sort -k 3’.  If your
script must also run on hosts that support only the traditional syntax,
it can use a test like ‘if sort -k 1 </dev/null >/dev/null 2>&1; then
...’ to decide which syntax to use.

答案2

它和 一样sort -k1,2nr -k3d

相关内容