Search code examples
stringbashunix

More elegant way to change format of date without multiple variables and substrings


I'm manipulating a string representing a date formatted as YYYY/MM/DD into a date formatted as MM/DD/YYYY. I'm doing this by extracting the month, day, and year into three separate variables using the cut command, then concatenating them back together. Is there a more elegant way of achieving this same result without relying on so many variables and cutting up and reassembling the string?


Solution

  • You can use sed. In the search string use groups (...) to capture the parts, then, in the replace string address these groups using \1, \2, ... .

    sed -E 's|(....)/(..)/(..)|\2/\3/\1|'
    

    alternatively, use awk

    awk -F/ '{print $2 "/" $3 "/" $1}'
    

    If you want to convert the date inside the variable $date use

    date=$(insertAnyCommandFromAbove <<< "$date")