Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk: "default" action if no pattern was matched?

Tags:

awk

I have an awk script which checks for a lot of possible patterns, doing something for each pattern. I want something to be done in case none of the patterns was matched. i.e. something like this:

/pattern 1/ {action 1}
/pattern 2/ {action 2}
...
/pattern n/ {action n}
DEFAULT {default action}

Where of course, the "DEFAULT" line is no awk syntax and I wish to know if there is such a syntax (like there usually is in swtich/case statements in many programming languages).

Of course, I can always add a "next" command after each action, but this is tedious in case I have many actions, and more importantly, it prevents me from matching the line to two or more patterns.

like image 892
Gadi A Avatar asked Jul 24 '13 10:07

Gadi A


1 Answers

You could invert the match using the negation operator ! so something like:

!/pattern 1|pattern 2|pattern/{default action}

But that's pretty nasty for n>2. Alternatively you could use a flag:

{f=0}
/pattern 1/ {action 1;f=1}
/pattern 2/ {action 2;f=1}
...
/pattern n/ {action n;f=1}
f==0{default action}
like image 54
Chris Seymour Avatar answered Oct 22 '22 12:10

Chris Seymour