As the third part of the awk command series, this time we'll look at how to filter text or strings based on user-defined specific patterns.
When you filter text, you may sometimes want to mark a file or a few lines in a line string based on a given condition or using a specific pattern that can be matched. It's easy to use awk to accomplish this task, and that's one of the few features that awk might be helpful to you.
Let's take a look at this example, for example, you have a shopping list with the food you want to buy, the name Food_prices.list, the name of the food it contains, and the corresponding price, as shown here:
$ cat Food_prices.list
No Item_name Quantity Price
1 Mangoes 10 $2.45
2 Apples 20 $1.50
3 Bananas 5 $0.90
4 Pineapples 10 $3.46
5 oranges 10 $0.78
6 Tomatoes 5 $0.55
7 Onions 5 $0.45
Then you want to use a (*) symbol to mark those foods that are more than $ $, so you can do this by running the following command:
$ Awk '/*\$[2-9]\. [0-9] [0-9]/{print $, $ $, $ $, "*";}/*\$[0-1]\. [0-9] [0-9] */{print;} ' food_prices.list
From the above output you can see that there is a (*) tag at the end of the line containing mango mangoes and pineapple pineapples. If you check their unit prices, you can see that their unit price is indeed more than $ $.
In this example, we have used two patterns:
First mode:/*\$[2-9]\. [0-9] [0-9] * * will be able to get those containing food price is greater than $ $ line,
Second mode:/*\$[0-1]\. [0-9] [0-9] * * will look for those rows where the food price is less than $ $.
What does the above command specifically do? This file has four fields, and when the pattern matches to a row containing a food price greater than $ $, it prints all four fields and adds a (*) symbol at the end of the line as a marker.
The second pattern simply outputs other rows containing less than $ $ per unit of food, as they appear in the input file food_prices.list.
This way you can use patterns to filter out items that cost more than $ $, and although there are some problems with the output, those lines with (*) symbols are not formatted to output as other rows, making the output less clear.
We also saw the same problem in the second part of the awk series, but we can use the following two ways to solve:
1, you can use the printf command as follows, but this use is long and boring:
$ Awk '/*\$[2-9]\. [0-9] [0-9]/{printf "%-10s%-10s%-10s%-10s\n", $, $ $, $ "*";}/*\$[0-1]\. [0-9] [0-9]/{printf "%-10s%-10s%-10s%-10s\n", $, $ $, $} ' food_prices.list
2, use the $ field. AWK uses variable 0来 to store the entire input line. This is handy for the above problem, and it's simple and fast:
$ Awk '/*\$[2-9]\. [0-9] [0-9] */{print $ "*";}/*\$[0-1]\. [0-9] [0-9] */{print;} ' food_prices.list