Awk multiple matching patterns

awk seems to match all the patterns matching the expression and take the appropriate action. Is there a priority that may be related?

For example, In the lines below starting with C # (comments), both patterns are matched and both actions are performed. I want the commented lines to correspond only to the first action.

/^#.*/ { // Action for lines starting with '#' } { // Action for other lines } 
+4
source share
3 answers

If you want to keep code that you already have mostly intact, you can simply use the awk next operator. When you encounter the next statement, awk skips processing the current record and continues to the next line.

So, if you put next in the lower 1st block, the second block will not be executed.

+7
source

Why not just simply if,else :

 awk '{ if ($0 ~ /^#/) // Action for lines starting with '#' else // Action for other lines }' 
+4
source

Another option is to use the template negation operator, '!', For the string "everything else" if your matching parameters are binary:

 /^#.*/ { // Action for lines starting with '#' } !/^#.*/ { // Action for other lines } 

Of course, your second template can also just match anything that doesn't start with a hash, i.e. /^►^#--------.*/

But presumably your example is simplification. For complex regular expressions, exact backward matching may not be possible. The negation operator simply makes it explicit and reliable.

And, as you already know, the ". *" Part is not needed.

+2
source

Source: https://habr.com/ru/post/1432131/


All Articles