1

I'm trying to use simple commands to extract data from a log file.

Here's a sample line from the file

128.101.35.183 - - [23/Mar/2008:00:03:10 +0000] "GET /javascript/email.js HTTP/1.1" 200 359 "http://www.cs.ucd.ie/Staff/AcademicStaff/bsmyth/"; "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12"

How can I get the date and time of the first and last log entry to the file displayed in the following format:

23/Mar/2008:00:03:10

with no other characters?

4

Try this to get the timestamps from the first and last lines in your log file:

{ head -n 1 my_log_file; tail -n 1 my_log_file; } | awk '{print $4}' | tr -d '['

As an aside, this looks like an Apache log, and you may wish to look into using Logstash to parse your structured logs.

  • 1
    Nice, but you might replace the head; tail bit with sed -n '1p;$p' for greater simplicity and speed. It will only open the file once instead of twice, and doesn't need shell braces to combine commands. – Wildcard Nov 15 '16 at 7:21
  • 1
    @Wildcard: it only runs one process, but it reads the whole file whereas tail seeks to the last block-or-so; this is faster if the logfile is very large, and logfiles sometimes are very large, especially the ones you need to look at when there's a problem. – dave_thompson_085 Nov 15 '16 at 10:17
0
awk -F"[][]" 'NR==1{sub(" .*","",$2);print $2}END{sub(" .*","",$2);print $2}' logfile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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