0

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?

user3196876
  • 187
  • 1
  • 12

1 Answers1

1

Assuming you are using bash

Syntax of while loop:

while test-commands; do consequent-commands; done

more info

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
a5hk
  • 7,532
  • 3
  • 26
  • 40
  • Tried both in the first case still gives me the same error. In the second case of FOR loop. it says: Syntax error: Bad for loop variable – user3196876 May 08 '14 at 21:32
  • @user3196876, Is your shell `bash`? the output of `readlink /bin/sh` – a5hk May 08 '14 at 21:38
  • I dont know I am using Ubuntu 12.04 I think its shell is bash. I am running following command: sh ./test.sh – user3196876 May 08 '14 at 21:45
  • @user3196876, What is the output of `readlink /bin/sh`? However you can try to change `#!/bin/sh` to `#!/bin/bash` in your code and use `bash ./test.sh`. – a5hk May 08 '14 at 21:53
  • tried #!/bin/bash with bash ./test.sh and it is throwing more errors now. The output of readlink /bin/sh is dash – user3196876 May 08 '14 at 22:00
  • @user3196876, in your ubuntu `sh` is linked to `dash`, thus when you use `sh ./test.sh` the file is executed with `dash`. but it should not have problems with `bash`, it is working for me. Anyways, what are the errors when you try to run the file with `bash`? – a5hk May 08 '14 at 22:12
  • ./test.sh: line 2: $'\r': command not found ./test.sh: line 3: syntax error near unexpected token `$'\r'' '/test.sh: line 3: `for (( i=0; i < 5; i++ )) – user3196876 May 08 '14 at 22:17
  • @user3196876,It is caused by `\r` you can use `dos2unix` to remove it, see [here](http://stackoverflow.com/questions/800030/remove-carriage-return-in-unix) – a5hk May 08 '14 at 22:26