Tuesday, October 2, 2012
11:12 PM

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



0 comments:

Post a Comment