Linux: GNU sort does not sort seq

1k Views Asked by At

Title sums it up.

$ echo `seq 0 10` `seq 5 15` | sort -n
0 1 2 3 4 5 6 7 8 9 10 5 6 7 8 9 10 11 12 13 14 15

Why doesn't this work?

Even if I don't use seq:

echo '0 1 2 3 4 5 6 7 8 9 10 5 6 7 8 9 10 11 12 13 14 15' | sort -n
0 1 2 3 4 5 6 7 8 9 10 5 6 7 8 9 10 11 12 13 14 15

And even ditching echo directly:

$ echo '0 1 2 3 4 5 6 7 8 9 10 5 6 7 8 9 10 11 12 13 14 15' > numbers
$ sort -n numbers 
0 1 2 3 4 5 6 7 8 9 10 5 6 7 8 9 10 11 12 13 14 15
4

There are 4 best solutions below

1
Chris Lutz On BEST ANSWER

sort(1) sorts lines. You have to parse whitespace delimited data yourself:

echo `seq 0 10` `seq 5 15` | tr " " "\n" | sort -n
1
Kamil Szot On

You have single line of input. There is nothing to sort.

0
Dirk is no longer here On

Because you need newlines for sort:

$ echo `seq 0 10` `seq 5 15` | tr " " "\\n" | sort -n | tr "\\n" " "; echo ""
0 1 2 3 4 5 5 6 6 7 7 8 8 9 9 10 10 11 12 13 14 15
$
2
Idelic On

The command as you typed it results in the sequence of numbers being all passed to sort in one line. That's not what you want. Just pass the output of seq directly to sort:

(seq 0 10; seq 5 15) | sort -n

By the way, as you just found out, the construct

echo `command`

doesn't usually do what you expect and is redundant for what you actually expect: It tells the shell to capture the output of command and pass it to echo, which produces it as output again. Just let the output of the command go through directly (unless you really mean to have it processed by echo, maybe to expand escape sequences, or to collapse everything to one line).