Process1
Process1

Reputation: 488

bash variables from nested for loops in awk

I want to simply use the two for loop variables in my awk code but I can't. Please help or guide me in the right direction.

for i in {30,60,100}; 
do 
   for j in {7,8}; 
   do 
       awk -v x=$i -v y=$j '{if ($NF <=x) print $0}' S_$i.txt > S_$i_$j.txt;
   done;
done

This was the error I received.

awk: fatal: cannot open file S_.txt for reading (No such file or directory). I saw this error.

Upvotes: 0

Views: 172

Answers (2)

Process1
Process1

Reputation: 488

Thanks for your quick response. However, I tried the following and it worked:

for i in {30,60,100}; 
    do 
     for j in {7,8}; 
      do 
       awk -v x=$i -v y=$j '{if ($NF <=x) print $0}' "S_"$j".txt" > "S_"$j"_"$i".txt";
      done;
    done;

Additionally, I realized that S_30.txt didn't exist. So when I changed it to "S_"$j".txt" it worked fine. My bad on that one.

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203512

S_$i_$j.txt is trying to access a variable named $i_. Use S_${i}_${j}.txt instead but also always quote your shell variables so it should really be:

awk -v x="$i" -v y="$j" '{if ($NF <= x) print $0}' "S_${i}.txt" > "S_${i}_${j}.txt"

or more awkishly:

awk -v x="$i" -v y="$j" '$NF <= x' "S_${i}.txt" > "S_${i}_${j}.txt"

and note that you never use y inside your awk script so it could just be:

awk -v x="$i" '$NF <= x' "S_${i}.txt" > "S_${i}_${j}.txt"

but then it's not clear why you'd want to create 2 copies of your output with each inner loop.

Whatever you're doing, though, could almost certainly be done much faster with a single call to awk than calling it multiple times within shell loops!

The problem you asked about has absolutely nothing to do with for loop variables in my awk code btw, it's all shell fundamentals.

Upvotes: 3

Related Questions