awk functions

awk supports functions and comes with a collection of built-in and useful functions.


User defined.

https://www.gnu.org/software/gawk/manual/html_node/User_002ddefined.html#User_002ddefined

  • function - required keyword
  • name( - required, alpha-numeric and underscore. Open parenthesis requird with no space.
  • [parm-list] - optional parameter list, comma delimited arguments.
  • ) - closing parenthesis.
  • { - open brace - start of code block.
  • actions - series of actions.
  • return argument - optional.
  • } - close brace, end of code block.

    function name( [parm-list] )
    {
      actions
      [return argument]
    }
    

    #f.awk
    #  For demo, use echo "" | awk -f f.awk
    # Note that awk uses a 2 pass process, and functions
    #   can be declared later in the script but are available
    #   earlier in the script.
    # 
    # The main block of code, the driver awk script is referred to 
    #   in comments as main.
    #
    BEGIN {
      # no space between function and (
      num=7;
      ary[1]=5;
    
      print "in main num=", num;
      print "and ary[1]=", ary[1];
    
      # scalar passed by value and array passed by reference
      ans=ask(num, ary, "boy" );
    
      # num not changed in main, ary is
      #  and ans contains the 'changed' num value
      print "in main num=", num, " and ans=", ans;
      print "and ary[1]=", ary[1];
      
      # name is created inside function amd continues outside
      # lname was a 'local' declared in the declaration, 
      #   not passed out
      print name, lname;
    }
    
    # By passing lname and num, scalars, in, they become local in the function.
    # Because ary is an array, it is passed by reference, which means not local.
    # Howowever, name, not previously defined, becomes a global scalar value.
    #
    # A function can return a single argument (string)
    # If a function is to 'return' multiple values, use an array created in
    #   main and pass it in. The function can then modify elements of the array
    #   which will then be available when function completes.
    #
    function ask (num, ary, lname)
    {
       print "lname in", lname;
       name="tim"
       lname="tank" 
       var="in ask, num=";
       print var, num;
       num=4
       print "Num tweaked=", num
       print "local var with value passed in", lname
    
       ary[1]=3
       # only one argument can be returned
       # if two or more 'arguments' provided, they are 
       #   concatenated.
       return num 1
    }
    

    Output :
    in main num= 7
    and ary[1]= 5
    lname in boy
    in ask, num= 7
    Num tweaked= 4
    local var with value passed in tank
    in main num= 7  and ans= 41
    and ary[1]= 3
    tim
    


    Pre-defined

  • Numeric
  • String