How could I write a regular expression for sed which extracts only the DATE field from log files accepting both of these date formats:

Jun  9 16:56:14 mailserver postfix ...
2017-06-04T06:59:36.984086+02:00 mailserver postfix ...

With awk printing the $1 column would work in the second case but not in the first.

migrated from serverfault.com Jun 20 '17 at 7:38

This question came from our site for system and network administrators.

  • Do you really mean you want just the date field, or did you want the date and time? (Your awk example would provide the datetime stamp, not just the date.) – roaima Jun 20 '17 at 10:54

Try this:

$ cat test.txt 
Jun  9 16:56:14 mailserver postfix ...
2017-06-04T06:59:36.984086+02:00 mailserver postfix ...
$ sed 's/^\([0-9:+\.T\-]*\|[A-Z][a-z]*\s*[0-9]*\s[0-9:]*\)\s.*/\1/' < test.txt 
Jun  9 16:56:14


  • Match on the beginning of line: ^
  • use backslashed parentheses to have your area of interest for the back reference in the substitution (see below), i.e. “the date” before “the rest of the log text”
  • in the parentheses: match both variants (use \| to denote the alternative of both sub-expressions)
  • after the parentheses: match the rest of the line, because we want to throw it away (it seems a bit counter intuitive at first, but see next point)
  • replace the whole line (that is why we match the rest) with the back reference to the date matching: \1
  • @roaima I can certainly do that, however the question indicates, that awk '{print $1}' gives the expected answer for the second case, which is: 2017-06-04T06:59:36.984086+02:00 – Stefan Moch Jun 20 '17 at 9:40

Your Answer

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