Guy
Guy

Reputation: 14790

using gawk in a shell script

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

Upvotes: 0

Views: 1466

Answers (4)

Dennis Williamson
Dennis Williamson

Reputation: 360035

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

Upvotes: 3

DigitalRoss
DigitalRoss

Reputation: 146043

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

Upvotes: 0

William Pursell
William Pursell

Reputation: 212248

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

Upvotes: 1

David Z
David Z

Reputation: 131560

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.

Upvotes: 0

Related Questions