For users who use the awk command, it is convenient to use comparison operators to filter text and strings when working with numbers or strings in a line of text.
In this section of the Awk series, we'll explore how to use comparison operators to filter text or strings. If you are a programmer, you should already be familiar with comparison operators, and for others, the comparison operator is described in the following sections.
What are the comparison operators in awk?
Comparison operators in awk are used to compare strings and or numeric values, including the following types:
>– Greater than
<– less than
>=– is greater than or equal to
<=– less than or equal
==– equals
!=– is not equal to
Some_value ~/pattern/– Returns True if Some_value matches pattern patterns
Some_value!~/pattern/– Returns True if Some_value does not match pattern patterns
Now let's use examples to familiarize ourselves with the various comparison operators in awk.
In this example, we have a file named Food_list.txt, which includes a list of different food purchases. I want to add (* *) The following line of items that have a food quantity less than or equal to 30.
File–food_list.txt
No Item_name Quantity Price
1 Mangoes 45 $3.45
2 Apples 25 $2.45
3 Pineapples 5 $4.45
4 Tomatoes 25 $3.45
5 Onions 15 $1.45
6 Bananas 30 $3.45
The common syntax for using comparison operators in AWK is as follows:
# Expression {action;}
To achieve the purpose, execute the following command:
# awk ' $ <= (printf "%s\t%s\n", $, "* *";} $ > {print $} ' Food_list.txt
No item_name ' Quantity price
1 Mangoes 45 $3.45
2 Apples 25 $2.45 * *
3 Pineapples 5 $4.45 * *
4 Tomatoes 25 $3.45 * *
5 Onions 15 $1.45 * *
6 Bananas 30 $3.45 * *
In the previous example, the following two important things happened:
First "Expression {action;}" In combination, the $ <= is "%s\t%s\n", $, "* *", and the number of rows that are less than or equal to 30 is printed and added (* *) at the back. The number of items is obtained by using the $ $ domain variable.
Second "Expression {action;}" In the group, the $ > {print $} Output quantity is less than or equal to 30 of the row.
Let me cite one more example:
# awk ' $ <= {printf '%s\t%s\n ', $, ' TRUE ';} $ > {print $} ' Food_list.txt
No Item_name Quantity Price
1 Mangoes 45 $3.45
2 Apples 25 $2.45
3 Pineapples 5 $4.45 TRUE
4 Tomatoes 25 $3.45
5 Onions $1.45 TRUE
6 Bananas 30 $3.45
In this example, we want to mark rows that are less than or equal to 20 by increasing (TRUE) at the end of the line.
Summarize
This is a guide to the introduction of comparison operators in awk, so you need to try other options and find more ways to use them.