Score:1

Conditionals in awk

jp flag

In bash I can do the shortcut condition for an if statement

  (( globrl == 1 )) && var=val

Is there something equivalent in awk, without having to use a direct if condition ?

Raffa avatar
jp flag
Yes `echo "2 3" | awk '($2 == 3) {print $2}'` or as compact as `echo "2 3" | awk '$2==3{print $2}'` ... Can be also something like `echo "2 3" | awk '/3/{print $1}'`
jp flag
Ok, so I can use `globrl == 1 { var = val }` then
Raffa avatar
jp flag
Yep ........... The whole concept of `awk` processing is a set of conditions and actions.
jp flag
I like it.......
jp flag
A top level construct ? Can it be used inside an awk function, testing a local variable?
Score:1
jp flag

Yes, ...

# If the second field is "3" print it
$ echo "2 3" | awk '{if ($2 == 3) print $2}'
3

# If the second field is "3" print it
$ echo "2 3" | awk '($2 == 3) {print $2}'
3

# If the second field is "3" print it
$ echo "2 3" | awk '$2==3{print $2}'
3

# If a match for "3" is in a line print the first field of this line
$ echo "2 3" | awk '/3/{print $1}'
2

# If the second field is "3" assign the value of "4" to the variable var then print it
$ echo "2 3" | awk '$2==3{var=4; print var}'
4

# If the second field is "3" assign the value of "yes" to the variable var or otherwise assign "no" to it and print it
$ echo "2 3" | awk 'var = $2 == 3 ? "yes" : "no" {print var}'
yes

# If the second field is "2" assign the value of "yes" to the variable var or otherwise assign "no" to it and print it
$ echo "2 3" | awk 'var=$2==2?"yes":"no"{print var}'
no

# Same as the above but utilizing the conditional expression with the ternary operator ‘?:’  in a function
$ echo "2 3" | awk 'function myfunc(field){var = field == 2 ? "yes" : "no"}; myfunc($2); {print var}'
no
jp flag
Could these commands be used inside an awk function?
Raffa avatar
jp flag
@Backy No, ... Functions have `{...}` as main grouping constructs ... Conditions and actions inside them can be in the form `if (...) ...`
Raffa avatar
jp flag
@Backy You can however utilize a conditional expression using the ternary operator `?:` in a function ... I have added an example for this one to the answer.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.