≡ Menu

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

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.

Add your comment

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

Comments on this entry are closed.

  • Gary Kronick February 17, 2010, 5:44 am

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

  • jameslee February 17, 2010, 11:40 pm

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

  • Ramesh Natarajan February 26, 2010, 5:05 pm

    @Jameslee,

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

  • Stuart August 2, 2011, 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.

  • Faheem September 6, 2011, 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,

  • Anonymous October 11, 2011, 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.

  • John November 17, 2011, 1:29 pm

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

  • student December 24, 2011, 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.

  • SANTOSH SHROFF V December 29, 2011, 11:19 pm

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

  • Carl June 20, 2012, 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

  • Tom January 22, 2013, 2:22 pm

    BEGIN {
    FS=”|”
    }
    {
    FLD_01=$1
    FLD_02=$2
    FLD_03=$3
    FLD_04=$4
    FLD_05=$5
    FLD_06=$6
    FLD_07=$7
    if ( FLD_05 = “Tom” ) FLD_08=”Me” ;
    else if ( FLD_05 = “John” ) FLD_08=”Friend” ;

    printf(“%s|%s|%s|%s|%s|%s|%s|%s\n”, FLD_01, FLD_02, FLD_03, FLD_04, FLD_05, FLD_06, FLD_07, FLD_08)
    }
    END {
    }

    I’m trying to get it to look at field 5, and then make a change to field 8.

    I run nawk -f run.awk tom

    When I run it, it changed all lines to Tom as the 5th field, and changes the 8th to me.

    What am I missing?

  • Rusty Shackleford June 26, 2013, 2:11 pm

    Use == instead of = in your if statement

  • rupali rane August 14, 2013, 4:14 am

    HI,
    i want to display those file which are containing AJZ word
    it should display all those file wich contains AJZ word from directory(means it should show only those files from directory which contains AJZ word)
    awk ‘{for(i=1;i<=NF;i++)if($i~/AJZ/)print$(i+1)}' test.txt

    plz give me the solution. i tired with this command but not getting result plz tell me the solution
    thanks in advance

  • nidhi October 11, 2014, 1:09 am

    Hi, In example 1, how to use awk if i want to know which marks is missing either $3 or $4 or $5

  • sayli December 6, 2014, 12:17 am

    I want how we can calculate nergy of each node using AWK file, I got many AWK file for calculating for calculating energy but its not properly work.. That awk files calculate only average energy of all node ,not calculate energy of each node

  • Bongo January 22, 2015, 5:17 am

    How do I find which student has scored the highest marks in $3?

  • Laks February 19, 2015, 9:02 pm

    Hi experts, am struggling get the below working as this is error out while passing the two arguments for column 2 and 3. Can someone help on how to get this working?

    #!/bin/sh
    COBDATE=`head -1 test.txt|cut -d’,’ -f2|cut -d’ ‘ -f6`
    PREVCOBDATE=`head -1 test.txt|cut -d’=’ -f2|head -c 9`
    awk -v VAR1=”$COBDATE” -v VAR2=$PREVCOBDATE
    ‘BEGIN{
    FS=”,”
    print “MIME-Version: 1.0”
    print “Content-Type: text/html”
    print “Content-Disposition: inline”
    print “””FileNames’$VAR1”$VAR2’DOMAIN NAMERemarks”
    }
    {
    printf “”
    for(i=1;i<=NF;i++)
    printf "%s”, $i
    print “”
    }
    END{
    print “”
    }’ test1.txt>mail.html

  • sarath October 12, 2015, 5:36 am

    Is it possible to have a if ladder inside awk?
    Like if(a>b)
    {
    if(c==0)
    }
    I need to evaluate two expressions here.Please give a response

  • Amit December 8, 2015, 6:26 pm

    Hi,
    I am struggling with some files.

    I have two tab separated values file, say

    File1.txt

    chr1 894573 rs13303010 GG
    chr2 18674 rs10195681 CC
    chr3 104972 rs990284 AA <— Unique Line
    chr4 111487 rs17802159 AA
    chr5 200868 rs4956994 **GG**
    chr5 303686 rs6896163 AA <— Unique Line
    chrX 331033 rs4606239 TT
    chrY 2893277 i4000106 GG
    chrY 2897433 rs9786543 GG
    chrM 57 i3002191 TT

    File2.txt

    chr1 894573 rs13303010 GG
    chr2 18674 rs10195681 AT
    chr4 111487 rs17802159 AA
    chr5 200868 rs4956994 CC
    chrX 331033 rs4606239 TT
    chrY 2893277 i4000106 GA
    chrY 2897433 rs9786543 GG
    chrM 57 i3002191 TA
    Desired Output:

    Output.txt

    chr1 894573 rs13303010 GG
    chr2 18674 rs10195681 AT
    chr3 104972 rs990284 AA <–Unique Line from File1.txt
    chr4 111487 rs17802159 AA
    chr5 200868 rs4956994 CC
    chr5 303686 rs6896163 AA =FNR&&($1″,”$2 in k)){k[$1,$2]=$0}END{for(K in k)print k[K]}’ file1 file2 >Output.txt

    Any suggestion will be helpful.

    Thanks, Amit