4 Awk If Statement Examples ( if, if else, if else if, :? )

by Sasikala on February 17, 2010

Linux Awk Tutorials - Conditional If Else Statement ExamplesThis 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)
{
	action1;
	action2;
}

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.

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.

Recommended Reading

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.

Share

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

{ 10 comments… read them below or add one }

1 Gary Kronick February 17, 2010 at 5:44 am

Here ya go: tertiary = coming next after the second and just before the fourth in position

2 jameslee February 17, 2010 at 11:40 pm

first of all i want to know what is “awk”..please give some tutorials from basic

3 Ramesh Natarajan February 26, 2010 at 5:05 pm

@Jameslee,

Read our awk introduction tutorial to understand the basics of awk.

4 Stuart August 2, 2011 at 1:27 pm

Example 1 should read:

awk ‘{
if ($3 ==”" || $4 == “” || $5 == “”)
print “Some score for the student”,$1,”is missing”;
}’ student-marks

NOTE: There is an extra ” ‘ ” character in your example.

5 Faheem September 6, 2011 at 10:30 pm

awk ‘{
if ($3 ==”" || $4 == “” || $5 == “”)
print “Some score for the student”,$1,”is missing”;’
}’ student-marks

There is a extra – ‘ – at the end of line ” print “Some score for the student”,$1,”is missing”;’ ” please remove it,

6 Anonymous October 11, 2011 at 1:18 pm

I am trying to use the following ‘awk’ command to print 60 6-column x 100 row text files to one large text file, i.e.

awk ‘{print $1, $2, $3, $4, $5, $6}’ textfile1.txt >> Batch_data_file.txt

The command works for all but four text files. For each of these four problem text files, it prints the first row of all six columns and nothing more. Why might ‘awk’ not be printing the remaining 99 rows?

Any help would be much appreciated.

7 John November 17, 2011 at 1:29 pm

This is one of the best tutorials I have found online. Well written and it has solved my problem. Thank you.

8 student December 24, 2011 at 6:39 am

Thanks for the examples.
Im not being able to find out what exactly the error is here:
#include
void main()
{
int numsweet;
double cost;
printf(“How many icecream do you want : “);
scanf(“%f, &numsweet”);
cost = 12.10 * numsweet;
if (numsweet > 1000)
{
printf(“The store does not have that much icecream in stock!”);
}
else
{
printf(“You have to pay $%f to the cashier!\n Thankyou!\n”, cost);
}
}

It gives a warning saying says “Possible use of numsweet before definition in funtion main. Plz help! any advice is welcomed.

9 SANTOSH SHROFF V December 29, 2011 at 11:19 pm

@STUDENT:the scanf statement should be as follows…
scanf(“%d”,&numsweet)

10 Carl June 20, 2012 at 8:25 am

Could you help me with the following syntax error? When I have one statement after the “if” , the program works. But when I want two statements after an “if” , I get errors.
Thanks,
Carl.

BEGIN { FS = “,” }
{ if ( $2 == “” && ( $6 == “Install” || $6 == “Add” || $6 == “New”) )
{
print $1″,”$2″,”$3″,”$4″,”$5″,”$6″,”$7″,”$8″,”$9 > “Email_Asset_Add” ;
print “$8″,”$9 > “Email_Asset_Add_Mitul” ;
}
else if ( $2 == “” && ( $6 == “Change” || $6 == “Update” || $6 == “Existing”) )
{
print $1″,”$2″,”$3″,”$4″,”$5″,”$6″,”$7″,”$8″,”$9 > “Email_Asset_Update” ;
print “$8″,”$9 > “Email_Asset_Update_Mitul” ;
}
}

awk -f awk_program test_email
awk: newline in string near line 23
awk: newline in string near line 28

Leave a Comment

Previous post:

Next post: