【发布时间】:2025-12-05 03:55:02
【问题描述】:
我试过下面的命令:
awk '/search-pattern/ {print $1}'
上述命令的else部分如何写?
【问题讨论】:
我试过下面的命令:
awk '/search-pattern/ {print $1}'
上述命令的else部分如何写?
【问题讨论】:
awk '{if ($0 ~ /pattern/) {then_actions} else {else_actions}}' file
$0代表整个输入记录。
Another idiomatic way
基于三元运算符语法selector ? if-true-exp : if-false-exp
awk '{print ($0 ~ /pattern/)?text_for_true:text_for_false}'
awk '{x == y ? a[i++] : b[i++]}'
awk '{print ($0 ~ /two/)?NR "yes":NR "No"}' <<<$'one two\nthree four\nfive six\nseven two'
1yes
2No
3No
4yes
【讨论】:
一个简单的方法是,
/REGEX/ {action-if-matches...}
! /REGEX/ {action-if-does-not-match}
这是一个简单的例子,
$ cat test.txt
123
456
$ awk '/123/{print "O",$0} !/123/{print "X",$0}' test.txt
O 123
X 456
等价于上述,但不违反DRY principle:
awk '/123/{print "O",$0}{print "X",$0}' test.txt
这在功能上等同于awk '/123/{print "O",$0} !/123/{print "X",$0}' test.txt
【讨论】:
{print ($0 ~ /pattern/)?text_for_true:text_for_false} 方法?
根据您想在 else 部分中执行的操作以及有关脚本的其他内容,在以下选项之间进行选择:
awk '/regexp/{print "true"; next} {print "false"}'
awk '{if (/regexp/) {print "true"} else {print "false"}}'
awk '{print (/regexp/ ? "true" : "false")}'
【讨论】:
awk 的默认操作是打印一行。鼓励您使用更惯用的 awk
awk '/pattern/' filename
#prints all lines that contain the pattern.
awk '!/pattern/' filename
#prints all lines that do not contain the pattern.
# If you find if(condition){}else{} an overkill to use
awk '/pattern/{print "yes";next}{print "no"}' filename
# Same as if(pattern){print "yes"}else{print "no"}
【讨论】: