Skip to content
Advertisement

Sorting an array of dates in bash

I want to sort an array of dates.

Example format: “2017-11-13_07-55-40” or Year-Month-Date_Hour-Minute-Second

array={"2017-11-13_09-55-42" "2017-11-13_08-30-40" "2017-11-13_07-55-40"}

Advertisement

Answer

Since your dates are already in YYYY-MM-DD-HH-MM-SS format, you can use numeric sort:

array=("2017-11-13_09-55-42" "2017-11-13_08-30-40" "2017-11-13_07-55-40")
sort -n < <(printf '%sn' "${array[@]}")

2017-11-13_07-55-40
2017-11-13_08-30-40
2017-11-13_09-55-42

To store output in another array use:

# populate another array with sorted date values
arr=($(sort -n < <(printf '%sn' "${array[@]}")))

# examine new array values
declare -p arr
declare -a arr=([0]="2017-11-13_07-55-40" [1]="2017-11-13_08-30-40" [2]="2017-11-13_09-55-42")
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement