Luca
Luca

Reputation: 1

for and awk in bash

I am experiencing some problems with a for cycle in bash, in combination with awk; I am running it in Ubuntu 14.04. This is the script I am writing:

#!/bin/bash

L=99;

for j in 1 2 3
do

 awk -v J=$j '

  BEGIN {active=0}
  /Sweep 6/ {active=1}
  /Energy/ {
  a=substr($6,1,length($6)-1);
  if ((active) && (a==J)) {
   getline;
   getline;
   getline;
   print a+1, $5
  }
 }
'

done

Without entering into the details of the text file I am processing, what the script does is just running what is in the cycle for j=1, instead of j=1, 2 and 3. Where is the problem?

Thanks in advance!

Upvotes: 0

Views: 175

Answers (2)

Jasen
Jasen

Reputation: 12422

only obvoius mistake I can see is you beed to reopen the file on each run of the loop, stdin to the loop or to the whole script won't work.

if the file's small and can't be rewound you could store it in a bash variable.

content="`cat`"
for j in 1 2 3
do
    echo "$content" |  awk 'etc...'
done

Upvotes: 0

fredtantini
fredtantini

Reputation: 16566

Your command is fine:

~$ cat >myfile
a
b
~$ for j in 1 2 3; do awk -v J=$j '{print J}' myfile; done
1
1
2
2
3
3

The only thing I see missing is the filename awk should parse.

Upvotes: 1

Related Questions