Reputation: 77
I'm writing a bash script for some automation, and I can't seem to find the best way of sorting an array that contains dates.
An example array:
dates=('180212', '110112', '040312')
The output should be as follows:
110112
180212
040312
I've tried to use sort
but it just sorts it as if it were a integer.
Could anyone advise on the best method to use? It doesn't necessarily have to sort either, I just need the oldest date from the array.
Thanks!
Upvotes: 0
Views: 934
Reputation: 12353
Example bash-script:
dates="180212 110112 040312"
min="999999"
for d in $dates
do
rdate="${d:4}${d:2:2}${d:0:2}"
if [ "$min" -gt "$rdate" ]
then
min=$rdate
fi
done
min="${min:4}${min:2:2}${min:0:2}"
echo $min
Works only with dates which are ddmmyy. The idea is to reverse the date in the format yymmdd and then find the minimum. Does the job in bash. Not beautiful though.
Upvotes: 1
Reputation:
You could swap the year and the day digits, and use sort
to sort the resulting values. Then take the oldest value and undo the swap. You can use sed
like this to do the swapping:
echo 112233 | sed 's/\(..\)\(..\)\(..\)/\3\2\1/'
This swaps the first two with the last two digits.
Upvotes: 1