All along, we used simple expressions to check whether the conditions were matched. What if you want to use more than one expression to check for a particular condition?
In this article, we'll look at how you can filter text and strings by combining multiple expressions--a composite expression--to check conditions.
The compound expression of awk can be represented by the combination operator of "and" && and representing "or" | Constitute.
The general wording of a composite expression is as follows:
(first expression) && (second expression)
The entire expression is true only if the first expression and the second expression are truth values.
(First expression) | | (second expression)
As long as the first expression is true or the second expression is true, the entire expression is true.
Note: Remember to enclose parentheses.
An expression can be composed of comparison operators, which can be viewed in section Fourth of the awk series.
Now let's use an example to deepen our understanding:
In this case, there is a text file Tecmint_deals.txt, which contains a random list of tecmint transactions containing the name, price, and kind.
Tecmint Deal List
No Name Price Type
1 Mac_os_x_cleanup_suite $9.99 Software
2 Basics_notebook $14.99 Lifestyle
3 Tactical_pen $25.99 Lifestyle
4 Scapple $19.00 Unknown
5 Nano_tool_pack $11.99 Unknown
6 Ditto_bluetooth_altering_device $33.00 Tech
7 Nano_prowler_mini_drone $36.99 Tech
We simply want to print out items that are more than $ Tech and whose type is "a", marked with (*) at the end of the line.
We will execute the following command.
# awk ' ($ ~/^\$[2-9][0-9]*\.[ 0-9][0-9]$/) && ($4== "Tech") {printf "%s\t%s\n", $, "*";} ' Tecmint_deals.txt
6 Ditto_bluetooth_altering_device $33.00 Tech *
7 Nano_prowler_mini_drone $36.99 Tech *
In this example, we used two expressions in a compound expression:
Expression 1: ($ ~/^\$[2-9][0-9]*\.[ 0-9][0-9]$/) find the line in which the transaction price exceeds $ $, that is, only if $ is the price satisfying/^\$[2-9][0-9]*\. [0-9] [0-9]$/values are true.
Expression 2: ($ = = "Tech") to find whether there is a kind of "Tech" transaction, that is, only if $ $ equals "Tech" value is the truth value. Keep in mind that this line is marked (*) only if the two states of the && operator, that is, two expressions are truth values.
Summarize
There are times when you have to use complex expressions to really meet your needs. Complex text or string filtering conditions can be easily resolved after you have mastered the usage of comparison and the compound expression operator.