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 ?
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.
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.
Sorting Numbers When you want to sort numbers, you need to add the -n flag, and sort will rearrange the numbers in ascending order.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With