OnWorks Linux and Windows Online WorkStations

Logo

Free Hosting Online for WorkStations

< Previous | Contents | Next >

Sorting An Array

Just as with spreadsheets, it is often necessary to sort the values in a column of data. The shell has no direct way of doing this, but it's not hard to do with a little coding:



#!/bin/bash


# array-sort: Sort an array a=(f e d c b a)

echo "Original array: ${a[@]}"

a_sorted=($(for i in "${a[@]}"; do echo $i; done | sort)) echo "Sorted array: ${a_sorted[@]}"

#!/bin/bash


# array-sort: Sort an array a=(f e d c b a)

echo "Original array: ${a[@]}"

a_sorted=($(for i in "${a[@]}"; do echo $i; done | sort)) echo "Sorted array: ${a_sorted[@]}"


When executed, the script produces this:



[me@linuxbox ~]$ array-sort Original array: f e d c b a Sorted array: a b c d e f

[me@linuxbox ~]$ array-sort Original array: f e d c b a Sorted array: a b c d e f


The script operates by copying the contents of the original array (a) into a second array (a_sorted) with a tricky piece of command substitution. This basic technique can be used to perform many kinds of operations on the array by changing the design of the pipeline.


Top OS Cloud Computing at OnWorks: