Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk multiple matching patterns

Tags:

awk

awk seems to match all the patterns matching an expression and executes the corresponding actions. Is there a precedence that can be associated ?

For eg. In the below, lines starting with # (comments) are matched by both patterns, and both actions are executed. I want commented lines to match only the first action.

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


{
    // Action for other lines
}
like image 477
Kumar Avatar asked Dec 16 '22 19:12

Kumar


2 Answers

If you want to keep the code you already have mostly intact, you could just use the awk next statement. Once you encounter the next statement, awk skips processing the current record and goes to the next line.

So if you put next into the bottom your 1st block the 2nd block wouldn't be executed.

like image 157
Levon Avatar answered Jan 04 '23 16:01

Levon


Why not simply if,else :

awk '{ if ($0 ~ /^#/) 
           // Action for lines starting with '#'
       else
           // Action for other lines
      }'
like image 35
Zulu Avatar answered Jan 04 '23 15:01

Zulu