Ada*_*tan 16 regex awk syntactic-sugar
以下AWK格式:
/REGEX/ {Action}
Run Code Online (Sandbox Code Playgroud)
将Action在当前行匹配时执行REGEX.
有没有办法添加一个else子句,如果当前行与正则表达式不匹配将执行,而不使用if-then-else显式,如下所示:
/REGEX/ {Action-if-matches} {Action-if-does-not-match}
Run Code Online (Sandbox Code Playgroud)
Zso*_*kai 17
不是那么短暂:
/REGEX/ {Action-if-matches}
! /REGEX/ {Action-if-does-not-match}
Run Code Online (Sandbox Code Playgroud)
但是(g)awk也支持三元运算符:
{ /REGEX/ ? matching=1 : matching = 0 ; if ( matching ==1 ) { matching_action } else { notmatching_action } }
Run Code Online (Sandbox Code Playgroud)
更新:
根据伟大的格伦杰克曼,你可以在比赛中分配变量,如:
m = /REGEX/ { matching-action } !m { NOT-matching-action }
Run Code Online (Sandbox Code Playgroud)
gle*_*man 14
还有next:
/REGEX/ {
Action
next # skip to the next line
}
{ will only get here if the current line does *not* match /REGEX/ }
Run Code Online (Sandbox Code Playgroud)