1

I've already greped a log file for multiline of date string:

2012-10-09 14:05:26  
2012-10-09 14:11:18  
2012-10-09 14:12:03  

Now I want to convert them to timestamp, and find which one is bigger than a value
date cmd:

date -d "2012-10-09 14:37:59" +%s  

I'm not sure how to do it with multiple lines, awk or other shell cmd.

1
  • 2
    In the format you show, you don't need conversion for making comparisons: string comparisons are okay. Commented Oct 9, 2012 at 8:54

2 Answers 2

3

This is just a simple example, a better solution should include parameter passing, error return testing, and more.

#!/bin/sh

SEARCH=`date -d "2012-10-09 14:11:09" +%s`
while read DATETIME ; do
    THIS=`date -d "$DATETIME" +%s`
    if [ "$SEARCH" -le "$THIS" ] ; then
        echo $DATETIME
    fi
done <<EOD
2012-10-09 14:05:26
2012-10-09 14:11:18
2012-10-09 14:12:03
EOD
Sign up to request clarification or add additional context in comments.

Comments

1

Using awk:

awk -v d="2012-10-09 14:07:26" '
    BEGIN { 
        FS = "[-: ]"; 
        split( d, arr, /[-: ]/ );
        date_timestamp = mktime( arr[1] " " arr[2] " " arr[3] " " arr[4] " " arr[5] " " arr[6] );
        if ( date_timestamp == -1 ) {
            printf "%s\n", "Bad format for input date";
            exit 1;
        }
    }
    { 
        if ( mktime( $1 " " $2 " " $3 " " $4 " " $5 " " $6 ) > date_timestamp ) { 
            print $0; 
        } 
    }
' infile

It yields:

2012-10-09 14:11:18  
2012-10-09 14:12:03

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.