3

I have the following simple script. However, it incorrectly gives the counter result to be 0.

#!/usr/local/bin/bash
f_name="test.stat"
S_Date="2012-02-10"
E_Date="2012-02-13"

awk 'BEGIN {FS="\t";s_time = mktime($S_Date);e_time = mktime($E_Date);counter=0}
     {if ($1 >= s_time && $1 <= e_time) counter++}
     END{print counter}' $f_name

The data file has the format: $Date $val

Sparhawk
  • 1,581
  • 1
  • 19
  • 29
Shuvo Shams
  • 633
  • 4
  • 10
  • 22
  • You'd better ask this on unix.stackexchange.com – Ali Mar 15 '12 at 20:57
  • 4
    It's an `awk` program and on topic for SO. – Jonathan Leffler Mar 15 '12 at 21:21
  • Seriously: how the heck does this question have almost 14,000 views and only two votes? (I was curious how someone had less than a hundred rep and 2 gold badges. This is how.) – neminem Jul 09 '14 at 18:18
  • 1
    I suspect it's because people come here hoping to find some insight about multiple conditions, and it turns out that the issue is really about variable quoting. – Jenn D. Oct 09 '14 at 06:37

1 Answers1

3

The awk command is in single quotes so $S_DATE and $E_DATE are being taken literally. You have a few options:

#!/usr/local/bin/bash
f_name="test.stat" S_Date="2012-02-10" E_Date="2012-02-13"

awk 'BEGIN {FS="\t";s_time = mktime('"$S_Date"');e_time = mktime('"$E_Date"');counter=0} {if($1 >= s_time && $1 <= e_time) counter++} END{print counter}' "$f_name"
#!/usr/local/bin/bash
f_name="test.stat" S_Date="2012-02-10" E_Date="2012-02-13"

awk "BEGIN {FS=\"\\t\";s_time = mktime($S_Date);e_time = mktime($E_Date);counter=0} {if(\$1 >= s_time && \$1 <= e_time) counter++} END{print counter}" "$f_name"

Or, my favorite:

#!/usr/local/bin/bash
f_name="test.stat" S_Date="2012-02-10" E_Date="2012-02-13"

awk "$f_name" <<EOF
BEGIN {
    FS="\t"
    s_time = mktime($S_Date)
    e_time = mktime($E_Date)
    counter=0
} 
{ if(\$1 >= s_time && \$1 <= e_time) counter++ } 
END{print counter}
EOF
Kevin
  • 53,822
  • 15
  • 101
  • 132
  • 1
    You could also pass the shell variables as awk variables: `awk -F '\t' -v s_date="$S_Date" -v e_date="$E_Date" 'BEGIN {s_time = mktime(s_date); e_time = mktime(e_date); ...` (this is *my* favourite ;) – glenn jackman Mar 16 '12 at 01:55
  • @Kevin, both of your first two options return 0 although the data file has dates that fall in that range – Shuvo Shams Mar 16 '12 at 19:12
  • @ glenn jackman, getting syntax error messages with your suggestion, should it be within quotes or something since its called within a bash script? – Shuvo Shams Mar 16 '12 at 19:17