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

GNU awk has switch statements:

$ cat tst1.awk
{
    switch($0)
    {
    case /a/:
        print "found a"
        break

    case /c/:
        print "found c"
        break

    default:
        print "hit the default"
        break
    }
}

$ cat file
a
b
c
d

$ gawk -f tst1.awk file
found a
hit the default
found c
hit the default

Alternatively with any awk:

$ cat tst2.awk
/a/ {
    print "found a"
    next
}

/c/ {
    print "found c"
    next
}

{
    print "hit the default"
}

$ awk -f tst2.awk file
found a
hit the default
found c
hit the default

Use the "break" or "next" as/when you want to, just like in other programming languages.

Or, if you like using a flag:

$ cat tst3.awk
{ DEFAULT = 1 }

/a/ {
    print "found a"
    DEFAULT = 0
}

/c/ {
    print "found c"
    DEFAULT = 0
}

DEFAULT {
    print "hit the default"
}

$ gawk -f tst3.awk file
found a
hit the default
found c
hit the default

It's not exaclty the same semantics as a true "default" though so it's usage like that could be misleading. I wouldn't normally advocate using all-upper-case variable names but lower case "default" would clash with the gawk keyword so the script wouldn't be portable to gawk in future.


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}

As mentioned above by tue, my understanding of the standard approach in Awk is to put next at each alternative and then have a final action without a pattern.

/pattern1/ { action1; next }
/pattern2/ { action2; next }
{ default-action }

The next statement will guarantee that no more patterns are considered for the line in question. And the default-action will always happen if the previous ones don't happen (thanks to all the next statements).

Tags:

Awk