awk tutorial: awk multiple conditions

Awk supports if else conditions judgment, and multiple conditions operations with && (and) or || (or) can be used.

syntax

awk -F "delimiter" '{
        if(condition-1 && condition-2 ){
                action-1;
        } else if (condition-3 || condition-4){
                action-2;
        } else {
                action-3;
        }
}' file

examples

Below we use specific cases to show you how to use awk multiple condition judgment.

The following is the test file content: ( Format: course1:score#course2:score#name

math:76#english:78#find
math:48#english:75#awk
math:98#english:66#sed
math:73#english:97#grep

Print the lines whose name is “awk” or whose math is greater than 95 or English is greater than 80.

In some cases, in order to express stronger logic, we will use if else and && (and) || (or) operations to achieve multiple conditions judgments.

➜  ~ awk -F "[:#]" '{
        if($5 == "awk"){
                print $0;
        } else if ($2 > 95 || $4>80){
                print $0;
        }
}' test.log

Of course, in the above example, we can also use only the || (or) operator.

➜  ~ awk -F "[:#]" '{
        if($5 == "awk" || $2 > 95 || $4 > 80){
                print $0;
        }
}' test.log

Add a Comment

Your email address will not be published.