1

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?

1
  • It would help us to come up with a better solution, if you'd tell us why (on what criteria are you picking those lines. Commented May 25, 2012 at 11:24

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

10 Comments

Thank you. Also, the advise about the array is very helpful: I will have to study some more awk :)
Sorry: the array only prints banana banana banana
@Edouard: Sorry, the c should be i as in arr[i] in the END block. I'll edit my answer.
thank you for the correction. One problem remains: array now prints apple cherry banana - is it possible using array to print in the correct order?
@Edouard: It's printing in the order that they appear in the file. What do you consider the proper order?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.