Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a log with following date format:

2013-12-14 18:53:33 aaaaaaaaaaaaaaaa
2013-12-14 18:53:33 bbbbbbbbb
2013-12-14 18:53:33 ccccccccccccccccccccc

What would be the simplest solution to convert it to

Dec 14 18:53:33 aaaaaaaaaaaaaaaa
Dec 14 18:53:33 bbbbbbbbb
Dec 14 18:53:33 ccccccccccccccccccccc

preferably in bash (or python)

share|improve this question

4 Answers 4

up vote 5 down vote accepted

You could do something like:

awk -F- 'BEGIN{split("Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec",m,",")}
         {print m[$2], substr($0,9)}'

Or:

awk -F- '{print substr("JanFebMarAprMayJunJulAugSepOctNovDec", \
         $2*3-2,3), substr($0,9)}'

Or:

sed 's/$/:01Jan02Feb03Mar04Apr05May06Jun07Jul08Aug09Sep10Oct11Nov12Dec/
     s/.....\(..\).\(.*\):.*\1\(...\).*/\3 \2/'
share|improve this answer

In bash, you could do the following:

$ tmpdate='2013-09-16 16:06:18,145-0500'
$ date +%c -d "$tmpdate"
Mon 16 Sep 2013 05:06:18 PM EDT

So, in the log line that you have, you could extract the date field as follows:

tmpdate=`echo "2013-12-14 18:53:33 aaaaaaaaaaaaaaaa" | cut -f1-2 -d ' '`

For more date formats, see: http://www.gnu.org/software/coreutils/manual/html_node/Date-input-formats.html#Date-input-formats

share|improve this answer

Use python convert.py < logfile with convert.py:

import sys
from datetime import datetime

for line in sys.stdin:
    dts = line[:19]
    d = datetime.strptime(dts, '%Y-%m-%d %H:%M:%S')
    print d.strftime("%b %d %H:%M:%S"), line[20:],

This can be further optimized as the hours, minutes, seconds don't have to be parsed. %b in strftime prints the month name according to your locale.

share|improve this answer

Python (input file - data.log, output file - out.log)

#!/usr/bin/env python
import datetime
import os
with open('data.log') as f, open('out.log', 'w') as f2:
  for line in f:
    log_date, text = line.rsplit(None, 1)
    log_date = datetime.datetime.strptime(log_date, '%Y-%m-%d %H:%M:%S')
    log_date = log_date.strftime('%b %d %H:%M:%S')
    f2.write('{} {}{}'.format(log_date, text, os.linesep))
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.