Awk Logical Operators – OR, AND, NOT

Boolean expressions are used to determine the occurrence of the given condition. Awk provides basic logical operators or and, or and not logic operators. In this tutorial, we will look basic usages of these logical operators. Boolean logic operators mainly used with conditional statements where we can get more information from the following tutorial.

Awk If, If Else , Else Statement or Conditional Statements

Example Data

While doing logic examples we will use following test data which file name is students.txt . The numbers are exam1, exam2, and exam3.

ismail 45 80 75 
ali    80 90 100 
elif   80 95 45

Awk AND Logic

and logic is used to check if all provided Boolean values are True . We use  && to specify and logic. The basic usage is providing two Boolean values and we can also provide more than 2 values. The best practice while using and logic is surrounding the operators and values with parenthesis ( ... ) . The syntax of and operator is like below.


In this example, we will check two exam1 and exam2 grades if they are over 50we will print the name of the student.

$ awk '{ if( $2>50 && $3>50 ) print $1 }' students.txt

As we can see we check columns 2 and 3 which matches with exam1 and exam2

Awk OR Logic

OR logic is used to check given conditions and if one of the conditions is true the whole or logic will return true. We will use || signs to specify OR logic. The syntax of OR logic is like below.


In this example, we will check all three exam degrees and find students who have to get a degree lower than 50 at least one time.

$ awk '{ if( $2<50 || $3<50 || $4<50 ) print $1 }' students.txt

$2 , $3 and $4 matches with exam1 , exam2 and exam3 we check all scores with Or logic if one of them is below 50 . If so we print the student name.

LEARN MORE  Awk Text Split and Delimit Examples

Awk NOT Logic

NOT logic provides given boolean value reverse. It is simple if given values is True after NOT logic return value will be false. If given boolean value is False after NOT logic return value will be true. Look following list. We will use ! sign as NOT operator.

  • ! True = False
  • ! False = True

Syntax is like below. Using parenthesis will made the script more reliable.


Now time to example we print student names those name is not ismail .

$ awk '{ if( !($1=="ismail") ) print $1 }' students.txt

Here our conditions is $1=="ismail" and reversed with ! NOT operator.

Leave a Comment