Edouard
Edouard

Reputation: 175

Correctly use variable in awk script

I have a file with many lines, like this:

 one     3456    orange
 two     6690    grape
 three   5570    apple
 four    6683    pear
 five    8847    cherry
 six     9035    banana

So I write a awk script to catch this output:

apple banana cherry

It looks like this:

awk '/three/ { a = $3}; /six/ { b = $3}; /five/ { c = $3} END {print  a" " b" "c}' <file

But this doesn't look the best way becuase I keep using $3 - how do I catch this variable to reuse it?

Upvotes: 1

Views: 205

Answers (1)

Dennis Williamson
Dennis Williamson

Reputation: 360665

There's nothing particularly wrong with doing it the way you are. If you use a variable, it will have to be repeated. However, you could use an array to accumulate your values.

Here is an example of using a simple variable:

awk '{var = $3} /three/ {a = var}; /six/ {b = var}; /five/ {c = var} END {print a, b, c}' file

Here is an example using an array:

awk '$1 ~ /^(three|six|five)$/ {arr[++c] = $3} END {for (i = 1; i <= c; i++) {printf "%s%s", delim, arr[i]; delim = OFS}; printf "\n"}' file

You don't need to use redirection. AWK can accept filenames as arguments.

In a print statement, commas substitute the value of OFS (by default a space) so you don't need to use " ".

In the array version, you can easily change the regex since it's all in one place.

Upvotes: 2

Related Questions