You were almost there, but you seem to have introduced a syntax error: $1=a4
would not check if the first column is equal to a4
, but assign the content of the awk
variable a4
(which is undefined and therefore empty) to the first column, thereby overwriting its content (which you already printed, so you didn't notice) and also evaluating to "false" because an uninitialized variable evaluates as "false". The same is true for your other comparisons. That is why you never get the "matched" condition as "true".
With the (small) required corrections, the program would look as follows:
awk '{if (($1=="a4" && $2=="b1") || ($1=="a4" && $2=="c2")) $3="matched"; else $3="-"} 1' data.txt
It works as follows:
- For every line, it will check whether the conditions you mention are met, and adds a third column to the line by setting
$3
to either -
or matched
.
- It will then print the current line including any modifications made. This is the meaning of the seemingly stray
1
outside of the rule block - awk
will print the current line including any previous modifications if it encounters a condition that evaluates to "true" outside of a rule.
Note that the above program is written explicitly for ease of understanding and to demonstrate the point. It can be shortened in your case because the condition on $1
is the same for both "allowed" cases of $2
:
awk '{if ($1=="a4" && ($2=="b1" || $2=="c2")) $3="matched"; else $3="-"} 1' data.txt
Also note that modifying any field will cause awk
to rebuild the line from its individual fields using the output field separator (defaults to one space), so if the input fields were separated by more than one space, the original formatting will be clobbered. If that is an issue, you should go with the "appending" strategy you already chose in the attempt you presented, although you should then print $0, ( your conditional string )
instead of $1, $2, ( your conditional string )
.