awk在命令行上工作但不在脚本中工作! (引用var的问题?)

时间:2014-10-11 16:38:57

标签: bash shell awk

我正在创建一个shell脚本来清​​除文件中超过2个月的条目,如下所示:  

我的测试文件:

1.2.3.8 2014-08-15
1.2.3.9 2014-09-08
1.2.3.10 2014-09-12
2.2.3.11 2014-08-08
2.2.3.1 2014-08-10
2.2.3.2 2014-07-31
2.2.3.3 2014-07-14

如果今天的日期是10月11日,则脚本必须只打印从1.x.x.x开始的IP。

在命令行中,这很有效:

$ awk '$2 > "2014-08-11"' MyTestFile
1.2.3.8 2014-08-15
1.2.3.9 2014-09-08
1.2.3.10 2014-09-12

但是,当我尝试将其放入shell脚本时,它会失败:( 脚本:

#!/bin/bash
Purge_Date=`date +%Y-%m-%d --date='2 month ago'`
echo "Purge all before : $Purge_Date"
awk '$2 > "$Purge_Date"' MyTestFile

执行:

$ ./dnsbl_purge.sh
Purge all before : 2014-08-11
1.2.3.8 2014-08-15
1.2.3.9 2014-09-08
1.2.3.10 2014-09-12
2.2.3.11 2014-08-08
2.2.3.1 2014-08-10
2.2.3.2 2014-07-31
2.2.3.3 2014-07-14

我几乎可以肯定问题来自var $ Purge_Date没有被解释(因为“'”),但我无法解决它。

1 个答案:

答案 0 :(得分:0)

Its because the `$Purge_Date` is a variable in the shell script which is unkown to the `awk`

传递$ Purge_Date to awk script as argument using the - v`选项。

#!/bin/bash
Purge_Date=`date +%Y-%m-%d --date='2 month ago'`
echo "Purge all before : $Purge_Date"
awk -v purge=$Purge_Date '$2 > purge' MyTestFile

此处-v purge=$Purge_Date将参数purge设置为您可以在awk中使用的$Purge_Date

相关问题