awk if else and nested if else statements with examples

Awk if else condition judgment statement are the capabilities we use most when using the awk command. The if else judgment statement can provide us with multiple condition judgment ability to solve branch processing problems.

This awk tutorial focuses on the if else conditional judgment statement.

We first create a test file, test-1.txt

123#192.168.1.33#google#20190622#/url/test

Example 1

In the following awk example, we will show you how to use the if statement to make a single conditional judgment.

awk if syntax

if(condition) {
    action;
}

➜ awk -F"#" '{if($1==123) print $2}' test-1.txt

Command explanation:
1. awk -F”#” – Press “#” to separate the fields: $1=123, $2= 192.168.1.33, $3 = google …
2. if($1==123) print $2 – Determine whether $1 is equal to “123”, that is, whether the content of the first column is “123”, and if it is, print the content of the second column.

Example 2

In the following awk example, we use the if() {} else {} statement to make a two-condition judgment.

if(condition) {
    action-1;
} else {
    action-2;
}

➜ awk -F"#" '{if($1==12) print $2;else print $0}' test-1.txt

Example 3

if() {
    ...
} else if {
    ...
} else {
    ...
}
➜ awk -F"#" '{if($1==12) print $1; else if($3 == "google") print $3; else print $0}' test-1.txt

Example 4

In the following example, we use awk multiple nested if else statements to make multiple conditional judgments.

if() {
    if() {
        ...
    } else {
        ...
    }
else {
    ...
}
➜ awk -F"#" '{
        if($1==123){
                print "true";
                if($3=="google") {
                        print $3;
                } else {
                        print "false"
                }
        } else {
                print $0
        }
}' test-1.txt
linux awk if else

Ok, here we have introduced how to use awk if else statements and if else nested statements in linux / unix for conditional judgment.

In the next article we will introduce how to use the awk ternary for conditional judgment.

2 Comments

Add a Comment

Your email address will not be published. Required fields are marked *