How to do a if else match on pattern in awk

2019-07-20 19:08发布

i tried the below command: awk '/search-pattern/ {print $1}' How do i write the else part for the above command ?

标签: shell awk grep
4条回答
小情绪 Triste *
2楼-- · 2019-07-20 19:47

The default action of awk is to print a line. You're encouraged to use more idiomatic 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"}
查看更多
孤傲高冷的网名
3楼-- · 2019-07-20 19:52

Classic way:

awk '{if ($0 ~ /pattern/) {then_actions} else {else_actions}}' file

$0 represents the whole input record.

Another idiomatic way based on the ternary operator syntax 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
查看更多
老娘就宠你
4楼-- · 2019-07-20 19:57

A straightforward method is,

/REGEX/ {action-if-matches...} 
! /REGEX/ {action-if-does-not-match}

Here's a simple example,

$ cat test.txt
123
456
$ awk '/123/{print "O",$0} !/123/{print "X",$0}' test.txt
O 123
X 456

Equivalent to the above, but without violating the DRY principle:

awk '/123/{print "O",$0}{print "X",$0}' test.txt

This is functionally equivalent to awk '/123/{print "O",$0} !/123/{print "X",$0}' test.txt

查看更多
Luminary・发光体
5楼-- · 2019-07-20 19:57

Depending what you want to do in the else part and other things about your script, choose between these options:

awk '/regexp/{print "true"; next} {print "false"}'

awk '{if (/regexp/) {print "true"} else {print "false"}}'

awk '{print (/regexp/ ? "true" : "false")}'
查看更多
登录 后发表回答