我尝试了以下命令:awk'/ search-pattern/{print $ 1}'如何为上述命令编写else部分?
awk '{if ($0 ~ /pattern/) {then_actions} else {else_actions}}' file
Run Code Online (Sandbox Code Playgroud)
$0 代表整个输入记录.
另一种
基于三元运算符语法的惯用方法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
Run Code Online (Sandbox Code Playgroud)
的默认操作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"}
Run Code Online (Sandbox Code Playgroud)
一个简单的方法是
/REGEX/ {action-if-matches...}
! /REGEX/ {action-if-does-not-match}
Run Code Online (Sandbox Code Playgroud)
这是一个简单的例子,
$ cat test.txt
123
456
$ awk '/123/{print "O",$0} !/123/{print "X",$0}' test.txt
O 123
X 456
Run Code Online (Sandbox Code Playgroud)
与上述等效,但不违反DRY原则:
awk '/123/{print "O",$0}{print "X",$0}' test.txt
Run Code Online (Sandbox Code Playgroud)
这在功能上等同于 awk '/123/{print "O",$0} !/123/{print "X",$0}' test.txt
根据您要在else零件中执行的操作以及有关脚本的其他操作,在以下选项之间进行选择:
awk '/regexp/{print "true"; next} {print "false"}'
awk '{if (/regexp/) {print "true"} else {print "false"}}'
awk '{print (/regexp/ ? "true" : "false")}'
Run Code Online (Sandbox Code Playgroud)