Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a if else match on pattern in awk

Tags:

grep

shell

awk

I've tried the below command:

awk '/search-pattern/ {print $1}'

How do I write the else part for the above command?

like image 450
RIshab R Bafna Avatar asked Jun 26 '17 07:06

RIshab R Bafna


People also ask

What is pattern matching in awk?

Any awk expression is valid as an awk pattern. The pattern matches if the expression's value is nonzero (if a number) or non-null (if a string). The expression is reevaluated each time the rule is tested against a new input record.

How do you use condition in awk?

The conditional statement executes based on the value true or false when if-else and if-elseif statements are used to write the conditional statement in the programming. Awk supports all types of conditional statements like other programming languages.

Can you use regex in awk?

In awk, regular expressions (regex) allow for dynamic and complex pattern definitions. You're not limited to searching for simple strings but also patterns within patterns.

What is awk '- F option?

The -f option only controls where the awk program is read from. If enabled, it means that the first filename is in fact the name of a file that contains the awk program. Otherwise, the first filename is the first file to start looking for patterns.


1 Answers

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
like image 145
George Vasiliou Avatar answered Nov 16 '22 00:11

George Vasiliou