How to do a if else match on pattern in awk

2019-07-20 19:15发布

问题:

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

回答1:

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


回答2:

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



回答3:

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"}


回答4:

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")}'


标签: shell awk grep