John Joel
John Joel

Reputation: 15

Unix : File DateFormat

acdbaqa@qaca010z:/tmp/joelj> ls -lrt hl.sh -rwxrwxrwx 1 acdbaqa acdba 2210 Jul 13 20:07 hl.sh

how to I convert the date format of any files to YYYYMMDD:HHSS

Upvotes: -2

Views: 5062

Answers (4)

e1000
e1000

Reputation: 59

On Mac OS, ls -alD %Y%m%d:%H%M will do exactly that

-rw-r--r--@   1 emilio  staff      1001 20150530:1540 yes.gif

Upvotes: 0

Mark Reed
Mark Reed

Reputation: 95335

If all you want is the modified time of a file, rather than ls, consider using the stat command:

stat -f %Sm -t %Y%m%d:%H%M%S hl.sh

That's the long form of the date/time format; it can be abbreviated to %F:%T.

If you don't have stat, you can use perl:

perl -MPOSIX -le 'print(strftime "%Y%m%d:%H%M%S", localtime((stat "hl.sh")[9]))'

You can pass the filename in outside the code to avoid quoting/interpolation issues:

perl -MPOSIX -le 'print(strftime "%Y%m%d:%H%M%S", localtime((stat $ARGV[0])[9]))' hl.sh

Upvotes: 1

yacc
yacc

Reputation: 3376

I'd favor the stat command but on Ubuntu I couldn't get it right. So here's my answer. It uses perl to do some string manipulation, so it might be considered a work-around somehow.

ls -lrt somefiles |perl -MDate::Manip -pe 's/^([-\w]+ \d+ \w+ \w+ \d+ )(\w+ +\d+ +[:\d]+)/$1.UnixDate(ParseDate($2),"%Y%m%d:%H%M")/e'

This recognizes date strings of the form %month %day %hour:%minute and converts it into the desired format.

Update: Now also works with the second date format which ls uses for files older than a year (%month %day %year).

Output for your file:

-rwxrwxrwx 1 acdbaqa acdba 2210 20170713:2007 hl.sh

Upvotes: 0

fvu
fvu

Reputation: 32973

In your example you seem to think 2210 is part of the date (it isn't, it's the file size) and your desired format leaves out the minutes. If both are unintentional, and you're using GNU ls, the --time-style option should do what you need:

ls -lrt --time-style="+%Y%m%d:%H%M%S"

which for your example will give more or less this result:

-rwxrwxrwx   1 acdbaqa  acdba       2210 20170713:200700 hl.sh

Upvotes: 1

Related Questions