Linux shell awk if

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.

Источник

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.

Читайте также:  Powered by arch linux

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.

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 /8+$/ 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 ~ /6+$/)) < 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.

Читайте также:  Hdx realtime media engine linux

Источник

4 Awk If Statement Examples ( if, if else, if else if, 😕 )

Linux Awk Tutorials - Conditional If Else Statement Examples

This article is part of the on-going Awk Tutorial Examples series. In our earlier awk articles, we discussed about awk print, awk user-defined variables, awk built-in variables, and awk operators. In this awk tutorial, let us review awk conditional if statements with practical examples.
Awk supports lot of conditional statements to control the flow of the program. Most of the Awk conditional statement syntax are looks like ‘C’ programming language. Normally conditional statement checks the condition, before performing any action. If the condition is true action(s) are performed. Similarly action can be performed if the condition is false. Conditional statement starts with the keyword called ‘if’. Awk supports two different kind of if statement.

  1. Awk Simple If statement
  2. Awk If-Else statement
  3. Awk If-ElseIf-Ladder

Awk Simple If Statement

Single Action: Simple If statement is used to check the conditions, if the condition returns true, it performs its corresponding action(s).

Syntax: if (conditional-expression) action
  • if is a keyword
  • conditional-expression – expression to check conditions
  • action – any awk statement to perform action.

Multiple Action: If the conditional expression returns true, then action will be performed. If more than one action needs to be performed, the actions should be enclosed in curly braces, separating them into a new line or semicolon as shown below.

Syntax: if (conditional-expression)

If the condition is true, all the actions enclosed in braces will be performed in the given order. After all the actions are performed it continues to execute the next statements.

Awk If Else Statement

In the above simple awk If statement, there is no set of actions in case if the condition is false. In the awk If Else statement you can give the list of action to perform if the condition is false. If the condition returns true action1 will be performed, if the condition is false action 2 will be performed.

Syntax: if (conditional-expression) action1 else action2

Awk also has conditional operator i.e ternary operator ( ?: ) whose feature is similar to the awk If Else Statement. If the conditional-expression is true, action1 will be performed and if the conditional-expression is false action2 will be performed.

Syntax: conditional-expression ? action1 : action2 ;

Awk If Else If ladder

if(conditional-expression1) action1; else if(conditional-expression2) action2; else if(conditional-expression3) action3; . . else action n;
  • If the conditional-expression1 is true then action1 will be performed.
  • If the conditional-expression1 is false then conditional-expression2 will be checked, if its true, action2 will be performed and goes on like this. Last else part will be performed if none of the conditional-expression is true.

Now let us create the sample input file which has the student marks.

$cat student-marks Jones 2143 78 84 77 Gondrol 2321 56 58 45 RinRao 2122 38 37 Edwin 2537 87 97 95 Dayan 2415 30 47

1. Awk If Example: Check all the marks are exist

$ awk '< if ($3 =="" || $4 == "" || $5 == "") print "Some score for the student",$1,"is missing";' >' student-marks Some score for the student RinRao is missing Some score for the student Dayan is missing

$3, $4 and $5 are test scores of the student. If test score is equal to empty, it throws the message. || operator is to check any one of marks is not exist, it should alert.

Читайте также:  Kali linux repository gpg

2. Awk If Else Example: Generate Pass/Fail Report based on Student marks in each subject

$ awk '< if ($3 >=35 && $4 >= 35 && $5 >= 35) print $0,"=>","Pass"; else print $0,"=>","Fail"; >' student-marks Jones 2143 78 84 77 => Pass Gondrol 2321 56 58 45 => Pass RinRao 2122 38 37 => Fail Edwin 2537 87 97 95 => Pass Dayan 2415 30 47 => Fail

The condition for Pass is all the test score mark should be greater than or equal to 35. So all the test scores are checked if greater than 35, then it prints the whole line and string “Pass”, else i.e even if any one of the test score doesn’t meet the condition, it prints the whole line and prints the string “Fail”.

3. Awk If Else If Example: Find the average and grade for every student

$ cat grade.awk < total=$3+$4+$5; avg=total/3; if ( avg >= 90 ) grade="A"; else if ( avg >= 80) grade ="B"; else if (avg >= 70) grade ="C"; else grade="D"; print $0,"=>",grade; > $ awk -f grade.awk student-marks Jones 2143 78 84 77 => C Gondrol 2321 56 58 45 => D RinRao 2122 38 37 => D Edwin 2537 87 97 95 => A Dayan 2415 30 47 => D

In the above awk script, the variable called ‘avg’ has the average of the three test scores. If the average is greater than or equal to 90, then grade is A, or if the average is greater than or equal to 80 then grade is B, if the average is greater than or equal to 70, then the grade is C. Or else the grade is D.

4. Awk Ternary ( ?: ) Example: Concatenate every 3 lines of input with a comma.

$ awk 'ORS=NR%3?",":"\n"' student-marks Jones 2143 78 84 77,Gondrol 2321 56 58 45,RinRao 2122 38 37 Edwin 2537 87 97 95,Dayan 2415 30 47,

We discussed about awk ORS built-in variable earlier. This variable gets appended after every line that gets output. In this example, it gets changed on every 3rd line from a comma to a newline. For lines 1, 2 it’s a comma, for line 3 it’s a newline, for lines 4, 5 it’s a comma, for line 6 a newline, etc.

Sed and Awk 101 Hacks, by Ramesh Natarajan. I spend several hours a day on UNIX / Linux environment dealing with text files (data, config, and log files). I use Sed and Awk for all my my text manipulation work. Based on my Sed and Awk experience, I’ve written Sed and Awk 101 Hacks eBook that contains 101 practical examples on various advanced features of Sed and Awk that will enhance your UNIX / Linux life. Even if you’ve been using Sed and Awk for several years and have not read this book, please do yourself a favor and read this book. You’ll be amazed with the capabilities of Sed and Awk utilities.

Источник

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