Pythalex
Pythalex

Reputation: 123

awk - regex assigned to variable - broken

Simple question to which I do not have the answer.

In a .awk script:

if ("test" ~ /^[[:alpha:]]+$/){
    print "MATCH"
} else {
    print "NOT MATCH"
}

will print MATCH

myvar = /^[[:alpha:]]+$/
if ("test" ~ myvar){
    print "MATCH"
} else {
    print "NOT MATCH"
}

will print NOT MATCH

I don't understand why. Is there an operator to get the value of myvar ? Is myvar just empty ?

Upvotes: 1

Views: 56

Answers (1)

oguz ismail
oguz ismail

Reputation: 50785

The standard says

When an ERE token appears as an expression in any context other than as the right-hand of the '~' or "!~" operator or as one of the built-in function arguments described below, the value of the resulting expression shall be the equivalent of:

$0 ~ /ere/

That means;

myvar = /^[[:alpha:]]+$/

is the same as

myvar = ($0 ~ /^[[:alpha:]]+$/)

You should wrap the ERE in double-quotes instead. Like

myvar = "^[[:alpha:]]+$"

Upvotes: 4

Related Questions