user3495008
user3495008

Reputation: 11

Convert timestamp Jan 05 11:45 to DD/MM/YY HH:MM format in Unix korn shell

My program goes as shown below where $i is a file.

TIMESTAMP=`ls -ltr $i | awk '{print $6,$7,$8;}'`

Output of this is Jan 6 12:13.

For sorting based on the date, I need to convert it to the format DD/MM/YY HH:MM.

Also please suggest if there is a way of sorting the files with the timestamp in the format Jan 6 12:13.

I am currently using Korn shell. Solaris 5.10.

Upvotes: 0

Views: 603

Answers (1)

mirabilos
mirabilos

Reputation: 5346

Under absolutely no circumstances, parse ls(1) output!

Instead, use the right tool for the job. If you need to sort ls output, use ls’ various sort options. If you need to do other processing, make use of a tool… in the Solaris 8 installation I have access to, GNU stat is installed, which makes this easy:

tg@stinky:~ $ stat -c '%y %n' /bin/[ck]sh
2008-07-08 14:16:07.000000000 +0200 /bin/csh
2008-06-10 16:28:32.000000000 +0200 /bin/ksh
tg@stinky:~ $ uname -a
SunOS stinky 5.8 Generic_117350-61 sun4u sparc SUNW,Sun-Fire-V240 Solaris

Otherwise, you could use scripting languages with stat(2) access, such as Perl, to display times for pathnames, like this (be aware of newlines in filenames, though):

tg@stinky:~ $ find /bin/[ck]sh | perl -MPOSIX -ne 'chomp; print POSIX::strftime("%d/%m/%Y %H:%M\n",localtime((stat)[9]));'
08/07/2008 14:16
10/06/2008 16:28

But, as others already pointed out in comments, %Y-%m-%d is indeed easier to sort.

The Korn Shell does not have any built-in functions for time manipulation.

The “magic chars in filenames”-safe version of this (also tested under Solaris 8) is:

find /bin/[ck]sh -print0 | perl -0 -MPOSIX -ne 'chomp; print POSIX::strftime("%d/%m/%Y %H:%M\n",localtime((stat)[9]));'

Of course, the find /bin/[ck]sh part is just an example, you can feed any pathname list you have to the command.

Upvotes: 2

Related Questions