Patrick
Patrick

Reputation: 339

Awk pass variable containing columns to be printed

I want to pass a variable to awk containing which columns to print from a file?

In this trivial case file.txt contains a single line

11 22 33 44 55

This is what I've tried:

awk -v a='2/4' -v b='$2/$4' '{print a"\n"$a"\n"b"\n"$b}' file.txt

output:

2/4
22
$2/$4
11 22 33 44 55

desired output:

0.5

Is there any way to do this type of "eval" of variable as a command?

Upvotes: 2

Views: 455

Answers (1)

John1024
John1024

Reputation: 113864

Here is one method for dividing columns specified in variables:

$ awk -v num=2 -v denom=4 '{print $num/$denom}' file.txt
0.5

If you trust the person who creates the shell variable b, then here is a method that offers flexibility:

$ b='$2/$4'; awk "{print $b}" file.txt
0.5
$ b='$1*$2'; awk "{print $b}" file.txt
242
$ b='$2,$2/$4,$5'; awk "{print $b}" file.txt
22 0.5 55

The flexibility here is due to the fact that b can contain any awk code. This approach requires that you trust the creator of b.

Upvotes: 1

Related Questions