简体   繁体   中英

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!

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM