Reputation: 557
I wish to loop through a M row X N column array of values and print them to the screen to be used for a later script, but I am having trouble with the loop and NR. Here's what I have so far:
#!/bin/bash
cat temp_file | wc -l > num_rows
i="0"
while [ $i -le `cat num_rows` ]; do
echo $i
awk 'NR==$i{print $1, $2}' temp_file
awk 'NR==$i{print $3, $4}' temp_file
((i++))
done
As you can see, I wish to use first find the number of lines, num_rows, and loop through each of those rows, and use AWK's NR function to go through each row and print columns one and two first, then columns three and four. The following error results when the above script runs:
0
awk: illegal field $(), name "i"
input record number 1, file temp_file
source line number 1
awk: illegal field $(), name "i"
input record number 1, file temp_file
source line number 1
1
awk: illegal field $(), name "i"
input record number 1, file temp_file
source line number 1
awk: illegal field $(), name "i"
input record number 1, file temp_file
source line number 1
2
awk: illegal field $(), name "i"
input record number 1, file temp_file
source line number 1
awk: illegal field $(), name "i"
input record number 1, file temp_file
source line number 1
3
awk: illegal field $(), name "i"
input record number 1, file temp_file
source line number 1
awk: illegal field $(), name "i"
input record number 1, file temp_file
source line number 1
4
and so on until the while loop completes. Any thoughts on how to fix this script, because right now, setting NR==$i does not work. Thanks for the help.
Upvotes: 3
Views: 10995
Reputation: 5768
You can pass i
to awk by
awk -v i=$i 'NR==i{print $1, $2}' temp_file
or
awk 'NR=='$i'{print $1, $2}' temp_file
Upvotes: 9