WernerCD
WernerCD

Reputation: 2157

AIX Bash Compare datetime strings

I have two log files.

Log File "Out":

Log File "Get":

If you notice the examples, the timestamp differences should be minimal. The issue is that sometimes the remote stops responding.

I'm getting better at bash, but I'm at a loss for a good way to compare the two time-stamps. Basically what I'm looking for is:

if DateDiff(TRX and PROC) > 15 minutes: Do Something Amazing

Upvotes: 1

Views: 2187

Answers (2)

WernerCD
WernerCD

Reputation: 2157

I think I have this working, as a slight variation of my actual question:

#!/usr/bin/perl -s
use Time::Local;

$OUT = `tail -500 /log/out.log | grep ^TRX  | tail -1 | cut -c46-62`;
$GET = `tail -500 /log/get.log | grep ^PROC | tail -1 | cut -c28-45`;
my $Start = getDate($OUT);
my $Finish = getDate($GET);

$DiffS = ( $Finish - $Start );
$DiffM = ( $Finish - $Start ) / 60;

print "$DiffS\n";
exit($DiffS);

sub getDate {
  $Y = substr $_[0], 0, 4;
  $M = substr $_[0], 4, 2;
  $D = substr $_[0], 6, 2;
  $h = substr $_[0], 9, 2;
  $m = substr $_[0], 11, 2;
  $s = substr $_[0], 13, 2;

  return timelocal($s,$m,$h,$D,$M,$Y);
}

Although this isn't exactly what I asked, it's allowed me to give a difference which I can use in a shell script that's already setup to if $I > $Diff then DO MAGICALLY THINGS

#!/bin/ksh
result=$(/usr/bin/logDiff)
print $result
if $result > 60
    ...

Upvotes: 1

diwhyyyyy
diwhyyyyy

Reputation: 6372

You can use sed to munge the timestamps into a format that (GNU) date can accept. So if you can get hold of GNU date on your AIX system, you can do it like this:

function toDateFormat() {
    local ts=$(echo "$1" | sed -E "s/$2.*Timestamp: ([0-9-]+)/\1/")

    ts=$(echo "$ts" | sed -E  "s/([0-9]{8})-([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/\1 \2:\3:\4/g")

    echo "$ts"
}

function compareLines() {
    local ts_a=$(date -d "$(toDateFormat "$1" "TRX")" +%s)
    local ts_b=$(date -d "$(toDateFormat "$2" "PROC")" +%s)

    local diff=$((ts_a-ts_b))

    if [[ diff -le 0 ]] ;
    then
        diff="$((0-diff))"
    fi

    echo "$diff"
}

A="TRX Sent: 02-000330408-01 Type: N Timestamp: 20130322-11474100"
B="PROC Sent: 02-000330408-01 Type: N Timestamp: 20130322-11374100"

res=$(compareLines "$A" "$B")

if [[ "$res" -ge $((15*60)) ]] ;
then
    echo "Do crazy stuff!"
fi

Upvotes: 1

Related Questions