0

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?

  • `old_date='2019/12/31'` ; `new_date=${old_date:5:2}'/'${old_date:8:2}'/'${old_date:0:4}`; `echo ${new_date}` => `12/31/2019`; benefit = eliminates overhead of invoking subprocesses for `cut` operations – markp-fuso Nov 25 '19 at 21:28
  • This question is closely related to https://stackoverflow.com/questions/2129123/rearrange-columns-using-cut. – Socowi Nov 25 '19 at 21:39

1 Answers1

2

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")
Socowi
  • 25,550
  • 3
  • 32
  • 54