Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting in shell script

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 ?

like image 424
user691197 Avatar asked Mar 01 '12 12:03

user691197


People also ask

What is sort in shell script?

The sort command is used in Linux to print the output of a file in given order. This command processes on your data (the content of the file or output of any command) and reorders it in the specified way, which helps us to read the data efficiently.

How do you sort files in shell script?

the -r flag is an option of the sort command which sorts the input file in reverse order i.e. descending order by default. Example: The input file is the same as mentioned above. 3. -n Option: To sort a file numerically used –n option.

How do I sort a bash script?

Sorting Numbers When you want to sort numbers, you need to add the -n flag, and sort will rearrange the numbers in ascending order.

How do you sort an array in shell scripting?

Example: Given array - (9, 7, 2, 5) After first iteration - (7, 2, 5, 9) After second iteration - (2, 5, 7, 9) and so on... In this way, the array is sorted by placing the greater element at the end of the array. Optimized Implementation: The above function always runs O(n^2) time even if the array is sorted.


1 Answers

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.

like image 97
l0b0 Avatar answered Oct 11 '22 10:10

l0b0