LamaEu LamaEu - 6 months ago 17
Bash Question

Passing an array to sort in BASH

Say I have an array consisting of lines such as:

arr[0] = 20160330 asdsa 24 asdsa 3 3000 054217542 30.3.2016
arr[1] = 20140102 asdsadsa 25 asdsadsaa 5 4500 534215365 2.1.2014
arr[2] = 20160306 dsasda 23 dsada 4 3200 537358234 6.3.2016


I now want to sort them by the first column, and print the them in the sorted order:

20140102 asdsadsa 25 asdsadsaa 5 4500 534215365 2.1.2014
20160306 dsasda 23 dsada 4 3200 537358234 6.3.2016
20160330 asdsa 24 asdsa 3 3000 054217542 30.3.2016


How do I use sort on an array?

Answer

If you are sure that none of the array elements contain newline characters, then try:

$ printf "%s\n" "${arr[@]}" | sort -nk1,1
20140102        asdsadsa 25 asdsadsaa 5 4500 534215365 2.1.2014
20160306        dsasda 23 dsada 4 3200 537358234 6.3.2016
20160330        asdsa 24 asdsa 3 3000 054217542 30.3.2016

Sorting and then removing the first number

Using cut:

$ printf "%s\n" "${arr[@]}" | sort -nk1,1 | cut -d" " -f2-
       asdsadsa 25 asdsadsaa 5 4500 534215365 2.1.2014
       dsasda 23 dsada 4 3200 537358234 6.3.2016
       asdsa 24 asdsa 3 3000 054217542 30.3.2016

Using sed:

$ printf "%s\n" "${arr[@]}" | sort -nk1,1 | sed 's/[[:digit:]]*[[:space:]]*//'
asdsadsa 25 asdsadsaa 5 4500 534215365 2.1.2014
dsasda 23 dsada 4 3200 537358234 6.3.2016
asdsa 24 asdsa 3 3000 054217542 30.3.2016