awk "for loop" question
I'm going through O'Reilly Press' sed and awk by Dougherty&Robins and am having trouble writing a simple "for" loop.
I'm writing a script called acro that accepts parameters from the command line to search a data file $ acro 1 2 3 4 5 I want each of the passed parameters to be searched through several fields of each record. My original solution to this was: awk '$2 == search' search=$1 array awk '$3 == search' search=$1 array awk '$4 == search' search=$1 array awk '$5 == search' search=$1 array awk '$6 == search' search=$1 array and so on for each of the command line parameters (search=$2 array, search=$3 array, search=$4 array, search=$5 array, search=$6 array). I decided I wanted to write a loop to save some lines of code and came up with this: for ( i=2; i=6; i++ ) awk '$i == search' search=$1 array The above script fails with this error message: $ ./acro 1 2 3 4 5 6 ./acro: line 6: syntax error near unexpected token `i=6' ./acro: line 6: `for i=2; i=6; i++ ' I don't understand the error message. How can I use a "for" loop to get this job done? Thanks. |
Are you trying to call awk from a shell script? If so, then it makes a difference which one you're using. (The for loops in Bourne shell, for example, only operate over lists.) If not, that for loop won't work the way you expect it to in Awk (or many other languages) because the conditional statement is wrong. You have an assignment to variable i, which since it is assigning 6 will always be true. So your loop would start at i=2 and continue going forever. You probably wanted "i <= 6" for your condition.
|
Yes. "acro" is a shell script under BASH. I'll try your suggestion.
Thanks much. |
Well, changing to "for ( i=2; i<=6; i++ )" didn't work. What do you mean "loops in Bourne shell, for example, only operate over lists"? How do I use a list to accomplish my end?
Thanks. |
A vanilla "for" loop in the Bourne shell works like this:
Code:
for i in 1 2 3; do Code:
i=1; Code:
for (( i=1; i < 4; i++ )); do Code:
for arg in $@; do |
start learning over here: http://www.linuxcommand.org/
And post back if you have problems .. |
All times are GMT -5. The time now is 07:48 PM. |