How to pass date range in awk as a variable

Here is my case.

bash ~]# TIME="2012-05-25 06:42:57"
bash ~]# echo "2012-05-25 00:16:51,610" | awk -v var=$TIME '{if ($0 < var) print $0}'

Then here is the error message

awk: 06:42:57
awk:   ^ syntax error

I just want to pass the date range to my awk command. How to do it? Please help. Thank.

Change case

START_TIME="2012-05-24 00:00:00"
END_TIME="2012-05-24 01:00:00"
echo "2012-05-24 00:10:10" | awk -v "START=$START_TIME" -v "END=$END_TIME" '{ if ( $0 > START && $0 < END) print $0 }'

It does not seem to work in IF conditions.

awk: { if ( $0 < START && $0 > END) print $0 }
awk:                           ^ syntax error

After the serval attempt, it seems that a solution with a different approach has been found.

echo "2012-05-24 00:10:10" | awk '{ if ( $0 > "'"$START_TIME"'" && $0 < "'"$END_TIME"'" ) print $0 }'

Not sure how to do this with the awk "-v" variable. Does anyone have caviar?

+3
source share
2 answers

Enter your variable when passing it to AWK:

echo "2012-05-25 00:16:51,610" | awk -v "var=$TIME" '{if ($0 < var) print $0}'
+7
source

, , , "END" . Awk END, BEGIN, . :

[ghoti@pc ~]$ START_TIME="2012-05-24 00:00:00"
[ghoti@pc ~]$ END_TIME="2012-05-24 01:00:00"
[ghoti@pc ~]$ echo "2012-05-24 00:10:10" | awk -v "START=$START_TIME" -v "END=$END_TIME" '{ if ( $0 < START && $0 > END) print $0 }'
awk: syntax error at source line 1
 context is
        { if ( $0 < START && $0 > >>>  END <<< ) print $0 }
awk: illegal statement at source line 1
[ghoti@pc ~]$ echo "2012-05-24 00:10:10" | awk -v s_time="$START_TIME" -v e_time="$END_TIME" '{ if ( $0 < s_time && $0 > e_time) print $0 }'
[ghoti@pc ~]$ 

, , - , , , .

if, , TRUE , , . , , , .

, . , gawk mktime(), .

[ghoti@pc ~]$ START_TIME="2012-05-24 00:00:00"
[ghoti@pc ~]$ END_TIME="2012-05-24 01:00:00"
[ghoti@pc ~]$ printf '2012-05-23 22:10:10\n2012-05-24 00:10:10\n2012-05-24 01:10:10\n' | gawk -v s_time="$START_TIME" -v e_time="$END_TIME" 'BEGIN { s=mktime(gensub(/[^0-9]/," ","G",s_time)); e=mktime(gensub(/[^0-9]/," ","G",e_time)); } { now=mktime(gensub(/[^0-9]/," ","G")); if ( now > s && now < e) print $0 }'
2012-05-24 00:10:10
[ghoti@pc ~]$ 

, gawk script :

BEGIN {
    s=mktime(gensub(/[^0-9]/," ","G",s_time));
    e=mktime(gensub(/[^0-9]/," ","G",e_time));
}
{
    now=mktime(gensub(/[^0-9]/," ","G"));
    if ( now > s && now < e) print $0;
}

, , / mktime() . .

+1

All Articles