1

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

Is it only possible to cut the first numbers so that the lines would start as: asdsadsa 25 asdsadsaa 5 4500 534215365 2.1.2014, etc..
@LamaEu Yes, I just added two methods for removing the leading number.
Hey, John. This doens't seem to work.` $ printf "%s\n" "${arr[@]}" | sort -nk1,1 | cut -d" " -f2-` did not cut the first column.
1

You can use process substitution with printf:

sort -nk1 <(printf "%s\n" "${arr[@]}")

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.