I am new user of gawk. I am trying to read trace file by putting a small code in a file and then by making that file executable. Following is what I am trying to do.
#!/bin/sh
set i = 0
while ($i < 5)
awk 'int($2)=='$i' && $1=="r" && $4==0 {pkt += $6} END {print '$i'":"pkt}' out.tr
set i = `expr $i + 1`
end
after this I am running following command:
sh ./test.sh
and it says:
syntax error: word unexpected (expecting do)
any help?
Assuming you are using bash
Syntax of while
loop:
while test-commands; do consequent-commands; done
For comparison using <
operator you need to use Double-Parentheses see Shell Arithmetic and Conditional Constructs.
To assign value to the variable you used in the code just write i=0
.
To access a shell variable in awk
use -v
option of awk
.
Thus your might be become like this:
i=0
while ((i < 5))
do
awk -v k=$i 'int($2)==k && $1=="r" && $4==0 {pkt += $6} END {print k":"pkt}' out.tr
i=`expr $i + 1`
done
Here the variable k
in awk
code, has the value of variable $i
from shell.
Instead of expr $i + 1
you can use $((i + 1))
or shorter $((++i))
Also you can use for
loop then your code becomes much cleaner:
for (( i=0; i < 5; i++ ))
do
awk -v k=$i 'int($2)==k && $1=="r" && $4==0 {pkt += $6} END {print k":"pkt}' out.tr
done