Hakan Baba
Hakan Baba

Reputation: 2025

awk: print one column or another depending on the value of another column

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

Upvotes: 0

Views: 3016

Answers (2)

Hakan Baba
Hakan Baba

Reputation: 2025

Using if-else statement in the pattern

awk '{if($3 == 1) {x = 1} else {x = 2}; {print $x}}'

Upvotes: 0

James Brown
James Brown

Reputation: 37404

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.

Upvotes: 4

Related Questions