Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a regular expression to a function in AWK

Tags:

awk

I do not know how to pass an regular expression as an argument to a function.

If I pass a string, it is OK,

I have the following awk file,

#!/usr/bin/awk -f

function find(name){
    for(i=0;i<NF;i++)if($(i+1)~name)print $(i+1)
}

{
    find("mysql")
}    

I do something like

$ ./fct.awk <(echo "$str")

This works OK.

But when I call in the awk file,

{
    find(/mysql/)
}  

This does not work.

What am I doing wrong?

Thanks,

Eric J.

like image 313
ericj Avatar asked Sep 02 '25 14:09

ericj


2 Answers

you cannot (should not) pass regex constant to a user-defined function. you have to use dynamic regex in this case. like find("mysql")

if you do find(/mysql/), what does awk do is : find($0~/mysql/) so it pass a 0 or 1 to your find(..) function.

see this question for detail.

awk variable assignment statement explanation needed

also http://www.gnu.org/software/gawk/manual/gawk.html#Using-Constant-Regexps

section: 6.1.2 Using Regular Expression Constants

like image 55
Kent Avatar answered Sep 05 '25 15:09

Kent


warning: regexp constant for parameter #1 yields boolean value

The regex gets evaluated (matching against $0) before it's passed to the function. You have to use strings.

Note: make sure you do proper escaping: http://www.gnu.org/software/gawk/manual/gawk.html#Computed-Regexps

like image 44
Karoly Horvath Avatar answered Sep 05 '25 16:09

Karoly Horvath