Better way to do tailing with awk

my current code:

varA=$(tail -200 /var/log/data.txt | egrep -c "Capital|capitol")
varB=$(tail -200 /var/log/data.txt | egrep -c "State|Country")
varC=$(tail -200 /var/log/data.txt | egrep -c "City|Town")

I want to do this a different way. something like:

AllVars=$(echo $(tail -200 /var/log/data.txt |  awk '/Capital|capitol/ {++c} END {print +c}' ;  awk '/State|Country/ {++c} END {print +c}' ; awk '/City|Town/ {++c} END {print +c}'))
varA=$(echo ${AllVars} | awk '{print $1}')
varB=$(echo ${AllVars} | awk '{print $2}')
varC=$(echo ${AllVars} | awk '{print $3}')

im pretty sure what i just did here is not efficient. i'm hoping someone can shorten it for me using awk.

You are right, this is not efficient. Pass through the file one time and use an awk script; the following shell script embeds the call to awk...

tail -200 /var/log/data.text | awk '
/[Cc]apital/ { varA=$0}
/State|Country/ { varB=$0 }
/City|Town/ { varC=$0}'

Just to point you in the right direction.

1 Like

You can accomplish the task efficiently in sh with a while loop to read and a case statement to match and assign.

Regards,
Alister

1 Like

If you want to put the output of the single awk into shell variables, you could try something like this:

read varA varB varC << EOF
$( 
  tail -200 /var/log/data.text | 
  awk '
    /Capital|capitol/ {a++}
    /State|Country/   {b++}
    /City|Town/       {c++} 
    END {print a+0,b+0,c+0}
  '
)
EOF
1 Like

An alternate method is

eval $(
  tail -200 /var/log/data.text |
  awk '
    /Capital|capitol/ {a++}
    /State|Country/ {b++}
    /City|Town/ {c++}
    END {print "varA="a+0, "varB="b+0, "varC="c+0}
  '
)
1 Like

thank you so much guys. this just saved me a lot of time!