Search code examples
bashvariablesawkdate-range

How to pass a date range to 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 a date range to my awk command. How to archive this? Please help. Thanks.

Modify the 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 seems not working in IF conditions.

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

After serval trying, seems found the solution with another approach.

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

Not sure how to do it with awk variable "-v". Anyone have idears?


Solution

  • Quote your variable when passing it to AWK:

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