Search code examples
awkconditional-statementschaining

Is condition chaining possible in awk?


Input file has in $1 two names. $2 is mostly filled but sometimes empty.

    1;   2;    3; 
Trump;  abc;
Obama;  
Obama;  abc;
Obama;  
Trump;  abc;

I am looking for a condition in AWK that fills $3 with the word "media" if name "Trump" or "Obama" occurs in $1 and $2 is emtpty.

I tried:

{if ($1=="Trump" || $1=="Obama" && $2==" ") {$3=="Media"};
print $0}

and

{if ($1=="Trump" && $2==" ") {$3=="Media"};
if ($1=="Obama" && $2==" ") {$3=="Media"};
print $0}

Solution

  • Considering that field separator is \t(tab) and each second field which is empty contains space " "(whitespace) you may use the following approach:

    awk -F"\t" '{OFS="\t"; if($1~/Trump|Obama/ && $2~/ /)$3="media"; print}' testfile 
    

    $1~/Trump|Obama/ - checks field value against regular expression


    The output:

    Trump   abc
    Obama           media
    Obama   abc
    Obama           media
    Trump   abc
    

    Alternative comparisons for second field:

    $2!~/[^ ]/

    $2~/[[:space:]]/ - POSIX class for whitespace characters