1829456 Members
1831 Online
109992 Solutions
New Discussion

AWK and functions

 
SOLVED
Go to solution
Dirk-jan hartman
Occasional Contributor

AWK and functions

Hello ,

I am trying to "beautify" my awk script, and to do that, use the ability to create user functions within the awk script.
But unfortunately, my brain seems to have set "STUPID_CODE_WRITER" bit to TRUE and hence, I can't get the code to work.

I have written a test script called "test" (for obvious reasons, to run this script, type ./test !).

This is the code :
#!/bin/ksh
echo "Hello" | awk '{

greetstring = Hello($0);
printf(greetstring);
function Hello(hellostring) {
returnstring = sprintf ("%s from DJ" , hellostring);
return returnstring
}

}'

and this is what HP-UX11 says:

hp21:/home/tso/djh/Tardis [djh] > ./test
syntax error The source line is 5.
The error context is
>>> function <<< hello(hellostring) {
awk: The statement cannot be correctly parsed.
The source line is 5.
awk: A return statement must be inside a function.
The source line is 7.
hp21:/home/tso/djh/Tardis [djh] >


If anyone has a clue as to what I am doing wrong, you help is greatly appreciated.

Thanks in advance, and have a splendid 2004!
Cheers,
DJ
2 REPLIES 2
curt larson_1
Honored Contributor
Solution

Re: AWK and functions

a function definiton can be placed anywhere in a script that a pattern-action rule appears. Typically, we put the function definitions at the top of the script before the patter-action rules.

echo "Hello" |
awk '
function Hello(hellostring) {
returnstring = sprintf ("%s from DJ" , hellostring);
return returnstring
}

{
greetstring = Hello($0);
printf(greetstring); # do you really want no format specifier here
}'
Dirk-jan hartman
Occasional Contributor

Re: AWK and functions

Thanks Curt!

The error I made was to put the function in the "body" of the awk statement, and it supposed to be declared before we arrive there.

It all works perfectly now, and I like to thank you for spending your time to help me out.

Cheers,
DJ