sorting in shell script

user691197 picture user691197 · Mar 1, 2012 · Viewed 29.6k times · Source

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 ?

Answer

l0b0 picture l0b0 · Mar 1, 2012

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.