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
![cat content](https://clitutorial.com/wp-content/uploads/2024/07/image-20-1024x177.png)
Examples
1) Split and Using a Single If Statement
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.
2) Split and Using a Single If-Else Statement
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
3) Split and use multiple if-else statements
if() {
...
} else if {
...
} else {
...
}
➜ awk -F"#" '{if($1==12) print $1; else if($3 == "google") print $3; else print $0}' test-1.txt
4) Split and use nested if-else statements
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
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.
if goole then false
oogle lie and examle is antisemantic