awk if else, if else if else and awk if else nested example

When we use linux awk, we usually need to perform the corresponding action according to certain conditions, then we will use the if else statement.

This Linux awk command tutorial introduces the use of awk if else statement.

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

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

linux awk if example

if() {
    ...
}

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

linux awk if else example

if() {
    ...
} else {
    ...
}

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

linux awk if else if else example

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

linux awk if else nested example

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

linux awk -F

The awk input delimiter defaults to a space, but you can also use the -F command parameter for fixed character delimitation.

Try:

create file test1.txt

run command

➜ cat test1.txt | awk -F':' '{if($1==1) print "A";else if($1==2) print "B";else print "C"}'

Related post:

awk command tutorial in linux/unix with examples and use cases
Awk tutorial: awk merge files base on the keyword
AWK tutorial: awk custom function and awk example
Awk tutorial: find and kill process use awk
Awk tutorial: awk -F and awk BEGIN{ FS … }
Awk tutorial: awk regex example
Awk tutorial: awk loop example: awk for and while
awk if else, if else if else and awk if else nested example
Awk tutorial: awk NR FNR difference
Awk tutorial: awk sort uniq
Awk tutorial: split on character awk or cut
Awk tutorial: awk newline character
Awk tutorial: three ways of awk execution
How to print tree directory structure in linux/unix
Linux shell batch move files, delete spaces, rename files
Docker common commands list with examples
sed command tutorial in linux/unix with examples and use cases

One Comment

Add a Comment

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