Skip to content
Advertisement

AWK: variables not remembered outside actions?

I have a script that will give the percent of logins that are mine. This is done by matching all users, store to variable, then match me only (jdoe). I then use a basic operation to get the percent of logins that are mine. I get the error:

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

It seems that the variables in my awk code are not being “remembered” outside the awk’s scope. How can I rewrite the script to make those variables global?

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

EDIT: It might be worth noting that I made a temporary file to store the results of “last” command to run the awk tests on.

Advertisement

Answer

Assign the output of awk to a variable, e.g:

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

Use expr to calculate the variables:

expr $foo / $bar
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement