LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   awk for-loop (https://www.linuxquestions.org/questions/linux-software-2/awk-for-loop-829894/)

babaqga 09-02-2010 02:57 AM

awk for-loop
 
Hi guys,

I am writing a simple bash script looking like this:
LOOP1
Code:

#!/bin/bash
...
echo $OUTPUT | awk '{
for (i="'"$NRCORES"'";i<="'"$ENDLOOP"'";i++)
print $i
}'

My problem is that the script doesn't output anything
BUT !
If I change it to the following:
LOOP2
Code:

#!/bin/bash
echo $OUTPUT | awk '{
for (i=8;i<=17;i++)
print $i
}'

It gives me what it is supposed to give (the 8-th to 17-th column of the $OUTPUT variable)

Strangely, if I echo $NRCORES or $ENDLOOP in the script I get 8 and 17 respectively, so in my view LOOP1 is exactly the same as LOOP2. However, awk doesn't seem to agree with me. In addition, I know for sure that when awk encounters a non-numeric variable in the print statement, it will take it as a zero and print the whole string. Therefore, I don't see what the problem can be.
WHAT IS WRONG WITH IT ?
please respond

druuna 09-02-2010 03:02 AM

Hi,

This works:
Code:

#!/bin/bash

OUTPUT="1234567890"
NRCORES=4
ENDLOOP=6

echo $OUTPUT | awk '{
for (i='$NRCORES';i<='$ENDLOOP';i++)
print i
}'

Mind the quoting and the print i (not $i)

Hope this helps.

babaqga 09-02-2010 03:08 AM

Quote:

Originally Posted by druuna (Post 4085775)
Hi,

This works:
Code:

#!/bin/bash

OUTPUT="1234567890"
NRCORES=4
ENDLOOP=6

echo $OUTPUT | awk '{
for (i='$NRCORES';i<='$ENDLOOP';i++)
print i
}'

Mind the quoting and the print i (not $i)

Hope this helps.

Yep, it helped, with the exception I want not the i itself, but the $i. Anyway, you were right for the quoting.

druuna 09-02-2010 03:17 AM

Hi,

Which $i are you talking about?

The for loop with the i=x;i<=y;i++ part is were i is generated (not $i). This is how awk works.

Maybe you should tell us what it is you are trying to accomplish so we can come up with code that suits that.

Hope this helps.

ghostdog74 09-02-2010 03:57 AM

use the -v option of awk to pass in shell variables to awk. Its "preferred" , than messy quoting.
Code:


#!/bin/bash
...
NRCORES="something"
ENDLOOP="something"

echo $OUTPUT | awk -vnc="$NCORES" -v el="$ENDLOOP" '{
for (i=nc;i<=el;i++)
  print $i
}'



All times are GMT -5. The time now is 06:58 AM.