Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWK: shortened if-then-else with regex

The following AWK format:

/REGEX/ {Action}

Will execute Action if the current line matches REGEX.

Is there a way to add an else clause, which will be executed if the current line does not matches the regex, without using if-then-else explicitly, something like:

/REGEX/ {Action-if-matches} {Action-if-does-not-match}
like image 574
Adam Matan Avatar asked Jan 23 '13 11:01

Adam Matan


3 Answers

Not so short:

/REGEX/ {Action-if-matches} 
! /REGEX/ {Action-if-does-not-match}

But (g)awk supports the ternary operator too:

{ /REGEX/  ? matching=1 : matching = 0 ; if ( matching ==1 ) { matching_action } else { notmatching_action } }

UPDATE:

According to the great Glenn Jackman you can assign variables on the match like:

m = /REGEX/ { matching-action } !m { NOT-matching-action }
like image 117
Zsolt Botykai Avatar answered Oct 10 '22 23:10

Zsolt Botykai


There's also next:

/REGEX/ {
    Action
    next # skip to the next line
}
{ will only get here if the current line does *not* match /REGEX/ }
like image 14
glenn jackman Avatar answered Oct 11 '22 01:10

glenn jackman


You can do a "trick". As you know AWK tries to match the input to each regex in order, to execute its block.

This code executes the second block if $1 is "1", else it executes the third block:

awk '{used = 0} $1 == 1 {print $1" is 1 !!"; used = 1;} used == 0 {print $1" is not 1 !!";}'

If the input is:

1
2

It prints:

1 is 1 !!
2 is not 1 !!
like image 1
arutaku Avatar answered Oct 11 '22 01:10

arutaku