Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting space delimited numbers with Linux/Bash

Tags:

linux

bash

Is there a Linux utility or a Bash command I can use to sort a space delimited string of numbers?

like image 585
syker Avatar asked Apr 12 '10 22:04

syker


People also ask

How do I sort with delimiter?

To sort by a delimiter pass the -t option to sort along with the delimiter value. For a CSV file this would be , . This can be combined with the -k option to sort on fields within a CSV. The result will be written to standard output.

How do I sort specific columns in Linux?

5. -k Option: Unix provides the feature of sorting a table on the basis of any column number by using -k option. Use the -k option to sort on a certain column. For example, use “-k 2” to sort on the second column.

How do I sort a table in bash?

Sort Command Options You can use the following options in conjunction with the raw command to modify how the values are sorted. -n – sorts in numerical values. -R – sort in random order but group the identical keys. -r – sort the values in reverse (descending order).


3 Answers

Here's a simple example to get you going:

echo "81 4 6 12 3 0" | tr " " "\n" | sort -g

tr translates the spaces delimiting the numbers, into carriage returns, because sort uses carriage returns as delimiters (ie it is for sorting lines of text). The -g option tells sort to sort by "general numerical value".

man sort for further details about sort.

like image 70
James Morris Avatar answered Sep 20 '22 15:09

James Morris


This is a variation from @JamesMorris answer:

echo "81 4 6 12 3 0" | xargs -n1 | sort -g | xargs

Instead of tr, I use xargs -n1 to convert to new lines. The final xargs is to convert back, to a space separated sequence of numbers.

like image 27
FranMowinckel Avatar answered Sep 20 '22 15:09

FranMowinckel


This is a variation on ghostdog74's answer that's too big to fit in a comment. It shows digits instead of names of numbers and both the original string and the result are in space-delimited strings (instead of an array which becomes a newline-delimited string).

$ s="3 2 11 15 8"
$ sorted=$(echo $(printf "%s\n" $s | sort -n))
$ echo $sorted
2 3 8 11 15
$ echo "$sorted"
2 3 8 11 15

If you didn't use the echo when setting the value of sorted, then the string has newlines in it. In that case echoing it without quotes puts it all on one line, but, as echoing it with quotes would show, each number would appear on its own line. This is the case whether the original is an array or a string.

# demo
$ s="3 2 11 15 8"
$ sorted=$(printf "%s\n" $s | sort -n)
$ echo $sorted
2 3 8 11 15
$ echo "$sorted"
2
3
8
11
15
like image 42
Dennis Williamson Avatar answered Sep 20 '22 15:09

Dennis Williamson