linux poison RSS
linux poison Email

Bash Script: How to sort an array

Here is simple & dirty trick to sort any types of element in an array ...
Feel free to copy and use this script.

Source: cat sort_array.sh
#!/bin/bash

array=(a x t g u o p w d f z l)
declare -a sortarray

touch tmp
for i in ${array[@]}; do
        echo $i >> tmp
        `sort tmp -o tmp`
done

while read line; do
        sortarray=(${sortarray[@]} $line)
done < tmp
rm tmp

echo "Here is the new sorted array ...."
echo ${sortarray[@]}

Output: ./sort_array.sh
Here is the new sorted array ....
a d f g l o p t u w x z





1 comments:

Anonymous said...

How about this?

#!/bin/bash

array=(a x t g u o p w d f z l)

sortarray=($(echo ${array[@]} | sed 's| |\n|g' | sort ))

echo "Here are the original and sorted arrays ...."
echo ${array[@]}
echo ${sortarray[@]}


Post a Comment

Related Posts with Thumbnails