tags:

views:

147

answers:

4

I want to do something of the sort:

for i in 1 2 3
do
   gawk '{if ($i==$2) {print $0;}}' filename
done

is this possible?

thanks

A: 

Well sure, it's possible, but it probably won't do what you want it to do.

...come to think of it, what do you want it to do? It's not really clear from what you've written. One thing you'll probably have to change is to replace the single quotes with double quotes because variables (like $i) aren't substituted into single-quoted strings.

David Zaslavsky
Also, `$2` will refer to the second field in the line being processed -- probably not the desired behavior.
Mark Rushakoff
+1  A: 

Assuming that you want the gawk script to be

{if ($1 == $2 ) ... }
{if ($2 == $2 ) ... }
{if ($3 == $2 ) ... }

you can do:

for i in 1 2 3
do
   gawk '{if ($'$i'==$2) {print $0;}}' filename
done
William Pursell
A: 

Two possible interpretations of your script come to mind:

  1. You really do want to search for "1", "2", and then "3" as the second field in filename
  2. You actually want to search for the 1'st shell script parameter, then the second, ...

Here are both versions of the loop:

for i in 1 2 3; do 
   gawk "{if (\"$i\"==\$2) {print \$0;}}" filename
done
for i in "$@"; do
   gawk "{if (\"$i\"==\$2) {print \$0;}}" filename
done
DigitalRoss
the "1 2 3" where just to get the feel. They could have been "i in 'a' 'b' 'c'", and so on.. So option 1 is what I was looking for
Guy
+2  A: 

In order to avoid ugly quoting, you can use gawk's variable passing feature:

for i in 1 2 3
do
    gawk -v param=$i '{if (param==$2) {print $0}}' filename
done
Dennis Williamson