AWK:使用正则表达式缩短了if-then-else [英] AWK: shortened if-then-else with regex

查看:364
本文介绍了AWK:使用正则表达式缩短了if-then-else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下AWK格式:

/REGEX/ {Action}

如果当前行与REGEX匹配,将执行Action.

Will execute Action if the current line matches REGEX.

是否有一种添加else子句的方法,如果当前行与正则表达式不匹配,则将执行该子句,而无需显式使用if-then-else,例如:

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}

推荐答案

不是很短:

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

但是(g)awk也支持三元运算符:

But (g)awk supports the ternary operator too:

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

更新:

根据出色的格伦·杰克曼,您可以在比赛中分配变量,例如:

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

m = /REGEX/ { matching-action } !m { NOT-matching-action }

这篇关于AWK:使用正则表达式缩短了if-then-else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆