0

The input to awk has multiple columns. I would like to print column $x or column $y depending on the value of column $z.

For example: The input is

3 2 1
4 5 6

I want to print first column if the third column is 1 and print second column otherwise.

Output should be

3
5
Hakan Baba
  • 1,897
  • 4
  • 21
  • 37
  • Similar questions are [q1](https://stackoverflow.com/questions/15160241/awk-print-columns-based-on-values-of-another-column) and [q2](https://stackoverflow.com/questions/14739057/awk-print-column-3-if-2-a-specific-value). But they print or do not print one column. I would like to print a different column depending on the condition. – Hakan Baba Jul 31 '17 at 20:02

2 Answers2

4

First some test data:

$ cat > file
1 2 2
1 2 1

Using conditional operator:

$ awk '{print ($3==1?$1:$2)}' file
2
1

If the value of the third field is 1, output the value of the first field, else the second field value.

James Brown
  • 36,089
  • 7
  • 43
  • 59
0

Using if-else statement in the pattern

awk '{if($3 == 1) {x = 1} else {x = 2}; {print $x}}'
Hakan Baba
  • 1,897
  • 4
  • 21
  • 37