Error using function in AWK code

Hi to all,

I have an AWK code that looks like this:

awk 'NR==FNR
        {
        #code to process file1 
         next
        }
        {
        #code to process file2 
        a=myfunction(x)
        }
        END {
            #Some code
             b=myfunction(x)
             
            }'file1 file2

As you can see, I need to call at least one time myfunction() when NR !=FNR and inside END{} statement.

I don't know where is the correct place to insert the function within the AWK code. If I put the function code in the part
when NR==FNR I receive errors and when I put the function in the part when NR !=FNR I receive the same error.

The function is a recursive function and I receive this error.

awk: cmd. line:4: function recurse(number,   ret)
awk: cmd. line:4: ^ syntax error
awk: cmd. line:16: return ret
awk: cmd. line:16: ^ `return' used outside function context

Where is the correct place put the function code?

Many thanks in advance

Hi,

Try to use function definition in BEGIN block cos your code calls the function before function definition i think.
END block execute at the end right.

Cheers,
Ranga:)

Probably best to define function up front:

awk '
  function recurse(number,   ret) {
        # Some code
        return ret
  }
  NR==FNR {
        #code to process file1 
         next
  }
  {
        #code to process file2 
        a=myfunction(x)
  }
  END {
        #Some code
        b=myfunction(x)
 
  }'file1 file2

Hi rangarasan and Chubler,

Thanks for your reply.

I've tried both and Chubler's suggestion worked for me.

Many thanks for your help guys.

Regards