10

I have an array

arr=( x11 y12 x21 y22 x31 y32)

I need to sort this array to

x11 x21 x31 y12 y22 y32

So, I need to sort both alphabetical and numerical wise

How do I perform this in shell script ?

If I use [ $i -le $j ], it says "integer expression expected".

And the strings may contain other characters also: x.1.1 or 1.x.1.

How do I do this ?

2
  • can u give me the complete syntax, I'm a beginner Commented Mar 1, 2012 at 12:58
  • Possible duplicate of How to sort an array in BASH Commented Oct 26, 2015 at 23:44

1 Answer 1

20

First split the array elements into lines (most *nix programs work with lines only):

for el in "${arr[@]}"
do
    echo "$el"
done

Then sort the lines:

for el in "${arr[@]}"
do
    echo "$el"
done | sort

Now you can assign that to an array again:

arr2=( $(
    for el in "${arr[@]}"
    do
        echo "$el"
    done | sort) )

Bingo:

$ echo "${arr2[@]}"
x11 x21 x31 y12 y22 y32

To understand how all this works, and how to change it if it doesn't do precisely what you want, have a look at the man pages:

man bash
man sort

See also How to sort an array in BASH.

Sign up to request clarification or add additional context in comments.

3 Comments

Can u give me the same syntax for a c shell. It says "Missing -" when run through cshell.
You should have specified that in the tags or the question. I don't know CSH.
But for numeric array, it will do lexicographic sort only. How can i sort numeric array then?

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.