AWK:变量不记得外面的行为?

时间:2017-03-19 22:35:43

标签: linux bash awk

我有一个脚本可以提供我的登录百分比。这是通过匹配所有用户,存储到变量,然后仅匹配我(jdoe)来完成的。然后我使用基本操作来获取我的登录百分比。我收到错误:

./loginPercent: line 13: eCount / totalCount: division by 0 (error token is "t")

我的awk代码中的变量似乎没有被记住"在awk的范围之外。如何重写脚本以使这些变量全局化?

#!/usr/bin/bash
last >> temp #Create a temp file that is filled with the last command output
awk 'BEGIN { totalCount=0;}
$1 ~ /[a-zA-Z0-9]/ {totalCount++; } #match anyone
END { print "Number of times anyone has logged in:",totalCount;}' temp

awk 'BEGIN { eCount=0;}
$1 ~ /jdoe/ {eCount++; } # match me
END { print "Number of times I have logged in:",eCount;}' temp

echo $eCount
echo $totalCount 
myPercent=$((eCount / totalCount)) 
echo $myPercent
rm temp #remove temp file so it doesn't change erroneously answers next time program is run

编辑:值得注意的是,我制作了一个临时文件来存储" last"命令运行awk测试。

2 个答案:

答案 0 :(得分:2)

您不需要多次遍历或临时文件,这一切都可以在一个脚本中完成

last | awk '$1 ~ /[a-zA-Z0-9]/ {totalCount++}
            $1=="jdoe"         {myCount++}
            END {print "Number of times anyone has logged in:",totalCount}' 
                 print "Number of times I have logged in:",myCount}
                 print "my percent:",totalCount?myCount/totalCount:0"}'

另外,不应该将totalCount等于行数吗?如果是这样,您可以在END区块中将其替换为NR并且不要打扰计数。

答案 1 :(得分:1)

将awk的输出分配给变量,例如:

foo=$(awk '$1 ~ /[0-9]/ { count++ ;} END { print count } '  file)
bar=$(awk '$1 ~ /[0-9]/ { count++ ;} END { print count } '  secondfile)

使用expr计算变量:

expr $foo / $bar