Linux awk if else

How to do a if else match on pattern in awk

Equivalent to the above, but without violating the DRY principle:

This is functionally equivalent to awk ‘/123/ !/123/’ test.txt

@EdMorton what is then the best option? The approach in George’s answer?

@fedorqui yes if the «else» part is also a print (which is also the 3rd option in my answer for that case). Otherwise the 1st or 2nd option in my answer.

The last suggestion (the one conforming to the DRY principle) should contain a ‘next’ like this: awk ‘/123/

Depending what you want to do in the else part and other things about your script, choose between these options:

awk '/regexp/ ' awk ' else >' awk '' 

The default action of awk is to print a line. You’re encouraged to use more idiomatic awk

awk '/pattern/' filename #prints all lines that contain the pattern. awk '!/pattern/' filename #prints all lines that do not contain the pattern. # If you find if(condition)<>else<> an overkill to use awk '/pattern/' filename # Same as if(pattern)else

This command will check whether the values in the $1 $2 and $7-th column are greater than 1, 2, and 5.

!IF! the values do not mach they will be ignored by the filter we declared in awk.

(You can use logical Operators and = «&&»; or= «||».)

You can monitoring your system with the «vmstat 3» command, where «3» means a 3 second delay between the new values

vmstat 3 | awk '($1 > 1) && ($2 > 1) && ($7 > 5)' 

I stressed my computer with 13GB copy between USB connected HardDisks, and scrolling youtube video in Chrome browser.

Источник

How to use conditional statement in awk command

The conditional statement is used in any programming language to execute any statement based on a particular condition. The conditional statement executes based on the value true or false when if-else and if-elseif statements are used to write the conditional statement in the programming. Awk supports all types of conditional statements like other programming languages. How different conditional statements can be used in awk command is shown in this tutorial.

Syntax:

The syntax for four types of conditional statements is mentioned below.

The statement executes when the if condition returns true.

The statement-1 executes when the if condition is true and the statement-2 executes when if return false.

if ( condition ) {
statement- 1
}
elseif {
statement- 2
}
elseif {
statement- 3
}
…….
else {
statement-n
}

This conditional statement is used for executing a statement based on multiple if condition. If the first condition is false then it checks the second condition. If the second condition is false then it checks the third condition and so on. If all conditions return false then it will execute the statement of else part.

Ternary operator can be used as an alternative of if-else statement. If the condition true the statement-1 will execute and if the condition false then statement-2 will execute.

Читайте также:  Linux ubuntu intel 64 bit

Example-1: Using simple if in awk

Create a text file named emplyee.txt with the following content. Suppose, you have to find out the department name, age, and salary of the employee whose id is 11002.

employee.txt

A simple if condition is used in the following script to search the id 11002 in the first field of the file. If the condition becomes true then it will print the values of the other fields of the corresponding line otherwise nothing will be printed.

$ awk ‘ <
if($1 ==»11002″)
<
print «Department Name: «,$2,»\n»;
print «Age: «,$3,»\n»;
print «Salary: «,$4,»\n»;

The id, 1102 exists in the file. So, it printed the other values of the employee.

Example-2: Using if-else in awk

Suppose, you want to print the salary information of the employees whose age is less than or equal to 40 and print the age information for other employees. The following awk script can do this task. There is only one employee in employee.txt file whose age is more than 40 and all other employee’s age is less than 40.

$ awk ‘ <
if($3 <
print «The salary of «,$1, » is «, $4, «\n»
>
else
<
print «The age of «,$1, » is «, $3, «\n»
>

The following output will appear after running the script.

Example-3: Using if-elseif in awk script

Create a text file named person.txt with the following content.

Create a awk file named if_elseif.awk with the following code to print the favorite color of each person whose name exists in the file. If-elseif statement is used in the script to do this task. The script will read the first field value of the file, employee.txt and check with a particular value. If the first if condition becomes false then it will check the second if condition and so on. When any if condition becomes true then a color value will be assigned. If all conditions become false then None will be assigned as the color value. The favorite color of each person will print or “No person found” will print if no person name matches.

if_elseif.awk

{
name = $1 ;
if ( name == «JACKSON» ) color = «Blue» ;
else if ( name == «MARTIN» ) color = «Black» ;
else if ( name == «LILY» ) color = «Red» ;
else if ( name == «ROBINSON» ) color = «White» ;
else color = «None» ;

if ( color ! = «None» ) print «The favorite color of » , name, «is » , color;
else print «No person found» ;

Run the following command to execute the file if_elseif.awk with person.txt

The following output will appear after running the command.

Example-4: Using ternary operator in awk

The third field of person.txt file contains the profession of each person. The following ternary operator reads each line of the file and matches the third field value with “Manager”. If the value matches then it will print the name of the person and otherwise it will print the gender of the person.

The following output will appear after executing the script. One person with “Manager profession exists in the person.txt. So, the name of one person is printed and gender is printed for other persons.

Example-5: Using multiple conditions in if statement

Logical OR and Logical AND can be used to define multiple conditions in the conditional statement of awk script. The following awk script reads each line of employee.txt and checks the age and designation with particular values. Logical AND is used in the if condition. When the age value is greater than or equal to 30 and designation is “HR” then the corresponding employee id and salary will print.

Читайте также:  Установить дискорд на linux

The following output will appear after executing the script. There is only one employee exists with the designation, “HR” in employee.txt. Id and salary information for this employee is printed here.

Conclusion:

Most common uses of the conditional statement of any standard programming are supported by awk command. How you can use single and multiple conditions in awk is explained by using very simple examples here. Hope after practicing these examples the learner will be able to use conditional statement properly in awk script.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Using if else Statements in Awk

Learn to use conditional statements in AWK. With the use of if else, you can write advanced AWK scripts.

AWK is a powerful scripting language that comes baked into the bash shell.

It is extremely versatile and can be used to write all kinds of data extraction scripts.

Conditional statements are an integral part of any programming or scripting language and AWK is no different.

In this tutorial, I’ll show examples of using if-else statements in AWK. Here’s the sample data on which I base my examples.

ID Name Age Subject
111 Farhaan 18 DevOps
89 Alex 21 SecOps
92 Ronn 22 IT
100 Robert 23 Commerce
102 Samantha 20 Cloud-Admin
105 Bob 21 Maths

I store it in students.txt . You can download it if you want to try the examples on your own.

1. The if statement in Awk

An if statement checks whether the condition is true or false. If the condition is true, then it executes the statements. Here’s a simple syntax for the if statement in awk:

Now, let’s use our sample data of the students.txt file and print the details of the student with ID 100 using if condition in AWK.

If statement example in AWK command

Here’s the execution of the above awk command: The entire above command can also be written in a single sentence like this:

2. The if else statement in Awk

In the previous example, there was only one condition and one action. The if else statement is slightly different from the if statement. The general format for the if else statement in awk is:

Here, if the condition is true, then command1 will be executed, and if the condition is false, then command2 from the else part will be executed. Let’s again take the student.txt data file. Suppose you want to get all the student’s name and their department whose age is less than or equal to 20 years. The AWK command could be like this:

AWK command if else statement example

Here’s the execution and output of the if else example: As you can see, there are only two students aged less than 20 years. The rest of the students are more than 20 years old. But there is a problem in the above example. It also considers the description of the table as real data and tells us that Student Name of age Age is more than 20 years old. Let’s rectify this with an if else-if statement.

Читайте также:  Linux соединить два компьютера между собой

3. The if else-if statement in Awk

With the if else if statements, the awk command checks for multiple conditions. If the first condition is false then it checks for the second condition. If the second condition is also false then it checks for the third condition and so on. It checks for all the conditions until one of the conditions is true. If no condition is satisfied, the else part is executed.

if(condition1) < command1 >else if(condition2) < command2 >else if(condition3) < command3 >. . . else

In the previous example, the output also considered the first line of the data which is just the description. Let’s put a condition to check if the age is a number or not. I am using a regex /3+$/ which means numeric values. The ~ means the argument has a number. And the negation operator before them means that the field should not have a number.

awk ' < if (! ($3 ~ /8+$/)) < print "Age is just a number but you do not have a number" >else if ($3 <20) < print "Student "$2,"of department", $4, "is less than 20 years old" >else < print "Student "$2,"of department", $4, "is more than 20 years old" >>' students.txt

if else if example with awk command

Let’s run it and focus on the first line of the output.

Bonus Tip: Use awk program file

If you find writing long awk programs in the terminal directly troublesome, use awk files. Create a new file and name it example.awk or anything you want. The extension doesn’t matter here. It just makes it easy to understand that the file is an awk program file. You put the content between the » that comes just after awk in the above examples.

awk -f example.awk students.txt

if else example with awk file

It will produce the same output that you saw previously.

More Bonus Tip: Use the ternary operator instead

Instead of using if else statements in awk, you can also use the ternary operator. Ternary expressions are the shorthand version of the if-else statement of the Awk. If the condition is true then command1 will execute; otherwise, if the condition is false then command2 is executed.

(condition) ? Command1:Command2

In this example $3 refers to the Age field. If the age is less than or equal to 20, then it will print the first command that displays «Age is less than 20». If the first part is False, it will execute the second command, «Age is over 20 «.

[email protected]:~$ awk '' students.txt Age over 20: Name Age less than 20: Farhaan Age over 20: Alex Age over 20: Ronn Age over 20: Robert Age less than 20: Samantha Age over 20: Bob 

Conclusion

In this guide, you learned different ways of using if-else statements in the AWK programming language. Using these statements, you can control the flow of a program, evaluate a condition, extract data from a file, etc. If you need a few more examples, this article will help you.

Источник

Оцените статью
Adblock
detector