Working with log files in linux/unix, you’ll inevitably come across the weirdness of a unix timestamp. It’s not intuitive working with the number of seconds since Jan 1 1970, so I rolled a little conversion utility in bash, called “utime2ymd”.
UPDATE #2:
This is unbelievably easy using GNU date, apparently. See the comments…
UPDATE: Slim, elegant version:
#!/bin/sh
echo $1 | awk '
{printf("%s", strftime("%Y.%m.%d ",$1));
printf("%s", strftime("%H:%M:%S \n",$1));
}'
ORGINAL oversized, but robust version (allows different timezones):
#!/bin/sh
USAGE="Usage: utime2ymd [local|gmt]
Convert 10-digit Unix timestamp to yyyymmdd.hhmmss format
Use local time zone (default) or UTC/GMT"
[ $1 ] || { echo -e $USAGE; exit 1 ; }
unixtime=`echo $1|cut -c -10`
if [ $2 ]
then qual2=`echo $2|awk '{print tolower($1)}'`
if [ "$qual2" = "gmt" ]
then thetime=`perl -e "print scalar(gmtime($unixtime))"`
fi
else
qual2="local"
thetime=`perl -e "print scalar(localtime($unixtime))"`
fi
YYYYMM=`echo $thetime | awk '{print $5 $2}' \
| sed 's/Jan/01/;s/Feb/02/;s/Mar/03/;s/Apr/04/;s/May/05/;s/Jun/06/;
s/Jul/07/;s/Aug/08/;s/Sep/09/;s/Oct/10/;s/Nov/11/;s/Dec/12/'`
DD=`echo $thetime | awk '{printf("%02d",$3)}'`
hhmmss=`echo $thetime | awk '{print $4}' | sed 's/://g'`
echo "$YYYYMM$DD.$hhmmss $qual2"
NOTE: There’s a similar command-line tool for the Windows environment, called ‘timetool‘. Wonder if I should write a linux version??
Or could try something like this
#!/bin/sh echo $1 | awk ' printf("%s", strftime("%Y.%b.%d",$1)); printf("%s.", strftime("%H:%M",$1));'Here’s an even simpler version using GNU date:
Localtime:
date -d @1235264470
Sat Feb 21 19:01:10 CST 2009
GMTime/UTC:
date -d -u @1235264470
Sun Feb 22 01:01:10 UTC 2009
From:
http://www.tburns.com/2009/date-conversion-using-the-linux-command-line/
@ropata:
You’ve left out the {}. The script doesn’t run as-is in gawk.