Score:0

Bash sort command numeric sort, fields and dictionary sort

dk flag

Can you explain sort +0nr -2 +2d please? This example is from https://www.grymoire.com/Unix/Awk.html The comment says:

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

Please explain every argument used.

Thanks!

hr flag
AFAIK that syntax is obsolete - see for example [Error “sort: cannot read: +1: no such file or directory”](https://unix.stackexchange.com/a/486729/65304)
Logan Lee avatar
dk flag
@steeldriver yeh but can you explain what they mean anyway?
waltinator avatar
it flag
Read `man sort` and `info sort`.
Score:1
hr flag

This is an obsolete (or at least obsolescent) "traditional" syntax for specifying field and column values, documented in 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’.

In the example you quote:

sort +0nr -2 +2d

there are two sets of specifiers: "+0 -2" and "-2". The first has A=0, B=2, Y absent and hence is equivalent to -k0+1,2 i.e. -k1,2 in in the modern 1-based indexing. The second has A=2 with both B and Y absent so becomes just -k3.

Letter options have their usual meanings i.e.

   -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

so the result is reverse numeric sort on the first two fields, -k1,2nr followed by dictionary sort on the third (and following) fields -k3d.

The info page advises against using this form of syntax:

   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.
Score:-1
dk flag

it is the same as sort -k1,2nr -k3d.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.