问题很可能只是您没有引用您的shell变量。看看这个例子:
$ foo='ab cd'
$ awk -v bar="$foo" 'BEGIN{print bar}'
ab cd
$ awk -v bar=$foo 'BEGIN{print bar}'
awk: fatal: cannot open file `BEGIN{print bar}' for reading (No such file or directory)
是的,我知道这是一个不同的错误信息——当你不加引号地使用shell变量时,会发生任何数量的事情,这取决于变量的值、目录的内容等等,其中一些非常糟糕,比如删除文件系统中的每个文件。
因此,请给您的变量加上引号:
-v last="$last" -v x="$x"
然后查看是否仍然存在问题。
顺便说一下,以下是如何使用GNU awk真正解决您的原始问题,并使用输入文件http://pastebin.com/BXmS4zLn:
$ cat tst.awk
BEGIN {
ARGV[ARGC++] = ARGV[ARGC-1]
mths = "JanFebMarAprMayJunJulAugSepOctNovDec"
if (days) { hours = days * 24 }
if (hours) { mins = hours * 60 }
if (mins) { secs = mins * 60 }
deltaSecs = secs
}
NR==FNR {
nr2secs[NR] = mktime($6" "(match(mths,$5)+2)/3" "$4" "gensub(/:/," ","g",$7))
next
}
nr2secs[FNR] >= (nr2secs[NR-FNR] - deltaSecs)
$ awk -v hours=1 -f tst.awk file
157.55.34.99 - - 06 Sep 2013 09:13:10 +0300 "GET /index.php HTTP/1.1" 200 16977 "-" "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)"
85.163.134.149 - - 06 Sep 2013 09:50:23 +0300 "GET /wap/wapicons/mnrwap.jpg HTTP/1.1" 200 1217 "http://mydomain.com/main.php" "Mozilla/5.0 (Linux; U; Android 4.1.2; en-gb; GT-I9082 Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"
83.113.48.218 - - 06 Sep 2013 10:13:07 +0300 "GET /english/nicons/word.gif HTTP/1.1" 200 803 "http://mydomain.com/french/details.php?eid=127928&cid=18&fromval=1&frid=18" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)"
$ gawk -v mins=60 -f tst.awk file
157.55.34.99 - - 06 Sep 2013 09:13:10 +0300 "GET /index.php HTTP/1.1" 200 16977 "-" "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)"
85.163.134.149 - - 06 Sep 2013 09:50:23 +0300 "GET /wap/wapicons/mnrwap.jpg HTTP/1.1" 200 1217 "http://mydomain.com/main.php" "Mozilla/5.0 (Linux; U; Android 4.1.2; en-gb; GT-I9082 Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"
83.113.48.218 - - 06 Sep 2013 10:13:07 +0300 "GET /english/nicons/word.gif HTTP/1.1" 200 803 "http://mydomain.com/french/details.php?eid=127928&cid=18&fromval=1&frid=18" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)"
$ gawk -v mins=20 -f tst.awk file
83.113.48.218 - - 06 Sep 2013 10:13:07 +0300 "GET /english/nicons/word.gif HTTP/1.1" 200 803 "http://mydomain.com/french/details.php?eid=127928&cid=18&fromval=1&frid=18" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)"
您可以指定days=或hours=或mins=或secs=变量,它会自动处理。如果您只需要获取最近1分钟的日志行(现在?),并想要看到一个一行代码的解决方案:
$ gawk 'NR==FNR {nr2secs[++nr] = mktime($6" "(match("JanFebMarAprMayJunJulAugSepOctNovDec",$5)+2)/3" "$4" "gensub(/:/," ","g",$7)); next} nr2secs[FNR] >= (nr2secs[nr] - 60)' file file
83.113.48.218 - - 06 Sep 2013 10:13:07 +0300 "GET /english/nicons/word.gif HTTP/1.1" 200 803 "http://mydomain.com/french/details.php?eid=127928&cid=18&fromval=1&frid=18" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)"
if
语句之前,但这完全是一个猜测,因为您没有发布实际的代码... - twalberg