2

I want to convert a date like

12-24-11 13:37

(MM-DD-YY MM:SS) to

11-12-24 13:37

(YY-MM-DD MM:SS)

is there anyway to do this?

Micheal Perr
  • 1,805
  • 5
  • 18
  • 24

3 Answers3

1

sed to the rescue:

$ echo 12-24-11 13:37 | sed 's#^\([0-9\-]\{5\}\)-\([0-9]\{2\}\)#\2-\1#'
11-12-24 13:37
phihag
  • 278,196
  • 72
  • 453
  • 469
1

No sed needed.

#!/bin/sh

input="12-24-11 13:37";

month="${input%%-*}";
input="${input#*-}";

day="${input%%-*}";
input="${input#*-}";

year="${input%% *}";
input="${input#* }";

echo "$year-$month-$day $input";

But if you do want to use external tools, might as well use one with a short regex

echo 12-24-11 13:37 | perl -pe 's/(.+)-(.+) /$2-$1 /'
phihag
  • 278,196
  • 72
  • 453
  • 469
jørgensen
  • 10,149
  • 2
  • 20
  • 27
0

This should point you in the right direction - http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/

T I
  • 9,785
  • 4
  • 29
  • 51
  • afaik, `date` can just print the current date, or *set* a new date. The OP wants to format an existing date. – phihag Dec 24 '11 at 12:54
  • @phihag If the OP used date, his invocation of date would either already include the + (to generate %m-%d-%Y), or his input would be something like "Sat Dec 24" (not %m-%d-%Y at all) instead :) – jørgensen Dec 24 '11 at 13:00
  • 1
    @phihag: Technically, `date` *can* usually print any arbitrary date. GNU date uses `-d` flag for this purpose, BSD date uses `-r` and `-v`. – GreyCat Dec 26 '11 at 01:17
  • http://stackoverflow.com/questions/6508819/convert-date-formats-in-bash is a good answer which seems to cover most basis – T I Dec 26 '11 at 01:58