user1179317
user1179317

Reputation: 2923

How to write awk function

I have a quick file file.awk with

function attr(attrname,str,  a) {
    if (!str) str=$0
    match(str,"@" attrname "=([^,/]*)",a)
    return a[1]
}

I am getting an error

awk: file.awk: line 139: syntax error at or near ,

where line 139 is the line with match()

Any idea whats wrong with the syntax?

Upvotes: 0

Views: 110

Answers (3)

RARE Kpop Manifesto
RARE Kpop Manifesto

Reputation: 2865

You absolutely don't need the match() function's capture array to get the attribute value you're seeking :

echo 'april@token=sha256hmackey/0.ts' \
\
| mawk 'function attr(___,_,__,____) { ____="\32\21"

     if(_=="") { 
        _=$(_<_) }

     return \
         sub("[@]"(___)"=[^,\\/]*",____"&"____,_) \
             \
              ? substr(_=__[split(_,__,____)-\
                    (_~_)],index(_,"=")+(_~"")) : ""
   } { 
       print attr("token") }'

sha256hmackey

Upvotes: 0

Mark
Mark

Reputation: 4453

As always, Ed Morton has it correct. The only reason I'm posting is that I can share with MacOS users that the awk man page includes the answer.

man awk yields:

  match(s, r)
          the position in s where the regular expression r occurs, or 0 if it does not.  The variables RSTART and RLENGTH are set to the  position  and
          length of the matched string.

So it is very clear that your call has an extra parameter.

I tried runnning awk with your function on MacOS and got this error:

awk: syntax error at source line 1 in function attr source file 
 context is
        match(str,"@" attrname >>>  "=([^,/]*)", <<< 

The "<<<" is indicating awk doesn't like that comma. This is similar to your error message:

syntax error at or near ,

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 204164

You're trying to use the non-POSIX 3rd arg to match() but not using GNU awk which supports it. See https://www.gnu.org/software/gawk/manual/gawk.html#String-Functions.

Upvotes: 1

Related Questions