Bash: How to Sort Strings with Numbers


Often you may want to use Bash to sort an array of strings that contain numbers.

You can use the sort statement with the version-sort option to do so:

printf '%s\n' "${athletes[@]}" | sort --version-sort

This particular example will sort the strings in the array named athletes based on both characters and numeric values.

You can also use the shorthand notation sort -V if you’d like:

printf '%s\n' "${athletes[@]}" | sort -V

The following example shows how to use this syntax in practice.

Example: How to Sort Strings with Numbers in Bash

Suppose that we create the following array in Bash named athletes that contains strings that represent ID numbers for various athletes:

athletes=(ID4 ID15 ID7 ID23 ID104 ID28 ID35)

Suppose that we would like to sort the strings in this array.

Suppose we attempt to use the sort statement by itself:

printf '%s\n' "${athletes[@]}" | sort

The following screenshot shows how to use this syntax in practice:

Notice that the numbers are not sorted in the correct order.

Instead, we must specify the version-sort option when sorting:

printf '%s\n' "${athletes[@]}" | sort --version-sort

The following screenshot shows how to use this syntax in practice:

Bash sort strings with numbers

Notice that the numbers are now sorted from smallest to largest since we specified version-sort when using the sort statement.

We could also sort based on the numbers from largest to smallest by adding the -r option (“reverse”) at the end:

printf '%s\n' "${athletes[@]}" | sort --version-sort -r

The following screenshot shows how to use this syntax in practice:

Bash sort strings with numbers in descending order

Notice that the strings are now sorted based on the numbers from largest to smallest.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Remove Last Element from Array
Bash: How to Get the Index of an Item in Array
Bash: How to Find Minimum and Maximum Values in Array

Leave a Reply