AWK: shortened if-then-else with regex

不问归期 提交于 2019-12-04 22:56:44

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 }

There's also next:

/REGEX/ {
    Action
    next # skip to the next line
}
{ will only get here if the current line does *not* match /REGEX/ }

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 !!
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!