如何将shell变量传递给awk?

时间:2012-03-15 20:51:20

标签: awk

我有以下简单的脚本。但是,它错误地将计数器结果设为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

数据文件的格式为:$ Date $ val

1 个答案:

答案 0 :(得分:3)

awk命令是单引号,因此$S_DATE$E_DATE字面意义。您有几个选择:

#!/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"

或者,我最喜欢的:

#!/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