loopsawkspplang

How to implement awk using loop variables for the row?


I have a file with n rows and 4 columns, and I want to read the content of the 2nd and 3rd columns, row by row. I made this

awk 'NR == 2 {print $2" "$3}' coords.txt

which works for the second row, for example. However, I'd like to include that code inside a loop, so I can go row by row of coords.txt, instead of NR == 2 I'd like to use something like NR == i while going over different values of i.

I'll try to be clearer. I don't want to wxtract the 2nd and 3rd columns of coords.txt. I want to use every element idependently. For example, I'd like to be able to implement the following code

for (i=1; i<=20; i+=1)
        awk 'NR == i {print $2" "$3}' coords.txt > auxfile
        func(auxfile)
end

where func represents anything I want to do with the value of the 2nd and 3rd columns of each row.

I'm using SPP, which is a mix between FORTRAN and C.

How could I do this? Thank you


Solution

  • It is of course inefficient to invoke awk 20 times. You'd want to push the logic into awk so you only need to parse the file once.

    However, one method to pass a shell variable to awk is with the -v option:

    for ((i=1; i<20; i+=2))  # for example
    do
        awk -v line="$i" 'NR == line {print $2, $3}' file
    done
    

    Here i is the shell variable, and line is the awk variable.