Search code examples
bashmacosdateterminalzsh

Converting dates in in MacOS Bash


First post! Learning bash and I have a list of dates from combined sources that I don't have control over that look like this:

1 July 2023
3 July 2023
10 July 2023
August 1, 2023
August 8, 2023
July 1, 2023
July 3, 2023
July 9, 2023
July 10, 2023

What I'm trying to do is convert them to 2023-07-01.

What I'm doing now is chopping up the variable and reordering things:

#   Grab Date From Filename
event_date_year=$(cut -d ' ' -f 6 <<<"$event_filename")
event_date_month=$(cut -d ' ' -f 4 <<<"$event_filename")
event_date_day="0"$(cut -d ' ' -f 5 <<<"$event_filename")
#   Trim unneeded zero
event_date_day=${event_date_day:-2}
event_date=$event_date_year"-"$event_date_month"-"$event_date_day

My next step is to loop through a list of months and replace them with numbers.

And I have to detect the "other" date format and fix those.

It occurs to me there's got be be a better way to do this, but I'm at a bit of a loss. I tried a few things with date, but it doesn't seem to detect the incoming date format.

Suggestions?


Solution

  • Use the date command to parse and format the date.

    Use a case statement to match the two different formats, <day> <month> <year> and <month> <day>, <year>.

    event_filename='1 July 2023'
    case "$event_filename" in
        [1-9]*) event_date=$(date -j -f '%d %B %Y' +'%Y-%m-%d' "$event_filename") ;;
        [A-Z]*) event_date=$(date -j -f '%B %d, %Y' +'%Y-%m-%d' "$event_filename") ;;
        *) echo "Unrecognized date format";
           exit 1
    esac
    echo "$event_date"