AWK built-in functions mainly include the following types:

Arithmetic Functions

Function Name Description Example
atan2( y, x ) Returns the arctangent of y/x.
$ awk 'BEGIN {
  PI = 3.14159265
  x = -10
  y = 10
  result = atan2 (y,x) * 180 / PI;

  printf "The arc tangent for (x=%f, y=%f) is %f degrees\n", x, y, result
}'

The output result is:

The arc tangent for (x=-10.000000, y=10.000000) is 135.000000 degrees
cos( x ) Returns the cosine of x; x is in radians.
$ awk 'BEGIN {
  PI = 3.14159265
  param = 60
  result = cos(param * PI / 180.0);

  printf "The cosine of %f degrees is %f.\n", param, result
}'

The output result is:

The cosine of 60.000000 degrees is 0.500000.
sin( x ) Returns the sine of x; x is in radians.
$ awk 'BEGIN {
  PI = 3.14159265
  param = 30.0
  result = sin(param * PI /180)

  printf "The sine of %f degrees is %f.\n", param, result
}'

The output result is:

The sine of 30.000000 degrees is 0.500000.
exp( x ) Returns the power function of x.
$ awk 'BEGIN {
  param = 5
  result = exp(param);

  printf "The exponential value of %f is %f.\n", param, result
}'

The output result is:

The exponential value of 5.000000 is 148.413159.
log( x ) Returns the natural logarithm of x.
$ awk 'BEGIN {
  param = 5.5
  result = log (param)

  printf "log(%f) = %f\n", param, result
}'

The output result is:

log(5.500000) = 1.704748
sqrt( x ) Returns the square root of x.
$ awk 'BEGIN {
  param = 1024.0
  result = sqrt(param)

  printf "sqrt(%f) = %f\n", param, result
}'

The output result is:

sqrt(1024.000000) = 32.000000
int( x ) Returns the value of x truncated to an integer.
$ awk 'BEGIN {
  param = 5.12345
  result = int(param)

  print "Truncated value =", result
}'

The output result is:

Truncated value = 5
rand( ) Returns an arbitrary number n, where 0 <= n < 1.
$ awk 'BEGIN {
  print "Random num1 =" , rand()
  print "Random num2 =" , rand()
  print "Random num3 =" , rand()
}'

The output result is:

Random num1 = 0.237788
Random num2 = 0.291066
Random num3 = 0.845814
srand( [Expr] ) Sets the seed value of the rand function to the value of the Expr parameter, or if the Expr parameter is omitted, uses the time of day. Returns the previous seed value.
$ awk 'BEGIN {
  param = 10

  printf "srand() = %d\n", srand()
  printf "srand(%d) = %d\n", param, srand(param)
}'

The output result is:

srand() = 1
srand(10) = 1417959587

String Functions

Function Description Example
gsub( Ere, Repl, [ In ] ) gsub is the abbreviation of global substitution. Except that all specific values of the regular expression are replaced, it performs exactly the same as the sub function.
$ awk 'BEGIN {
    str = "Hello, World"

    print "String before replacement = " str

    gsub("World", "Jerry", str)

    print "String after replacement = " str
}'

The output result is:

String before replacement = Hello, World
String after replacement = Hello, Jerry
sub(regex,sub,string) The sub function performs one substring replacement. It replaces the first occurrence of a substring with regex. The third parameter is optional, defaulting to $0.
$ awk 'BEGIN {
    str = "Hello, World"

    print "String before replacement = " str

    sub("World", "Jerry", str)

    print "String after replacement = " str
}'

The output result is:

String before replacement = Hello, World
String after replacement = Hello, Jerry
substr(str, start, l) The substr function returns a substring of the str string starting from the start-th character with length l. If the value of l is not specified, it returns the suffix substring of str starting from the start-th character.
$ awk 'BEGIN {
    str = "Hello, World !!!"
    subs = substr(str, 1, 5)

    print "Substring = " subs
}'

The output result is:

Substring = Hello
index( String1, String2 ) In the string specified by the String1 parameter (where the parameter specified by String2 appears), return the position, numbered from 1. If the String2 parameter does not appear in the String1 parameter, return 0 (zero).
$ awk 'BEGIN {
    str = "One Two Three"
    subs = "Two"

    ret = index(str, subs)

    printf "Substring \"%s\" found at %d location.\n", subs, ret
}'

The output result is:

Substring "Two" found at 5 location.
length [(String)] Returns the length (in characters) of the string specified by the String parameter. If the String parameter is not given, returns the length of the entire record ($0 record variable).
$ awk 'BEGIN {
    str = "Hello, World !!!"

    print "Length = ", length(str)
}'

The output result is:

Substring "Two" found at 5 location.
blength [(String)] Returns the length (in bytes) of the string specified by the String parameter. If the String parameter is not given, returns the length of the entire record ($0 record variable).  
substr( String, M, [ N ] ) Returns a substring having the number of characters specified by the N parameter. The substring is taken from the string specified by the String parameter, with its characters starting at the position specified by the M parameter. The M parameter is specified with the first character in the String parameter as number 1. If the N parameter is not specified, the length of the substring will be the length from the position specified by the M parameter to the end of the String parameter.
$ awk 'BEGIN {
    str = "Hello, World !!!"
    subs = substr(str, 1, 5)

    print "Substring = " subs
}'

The output result is:

Substring = Hello
match( String, Ere ) In the string specified by the String parameter (where the extended regular expression specified by the Ere parameter appears), return the position (in character form), numbered from 1, or return 0 (zero) if the Ere parameter does not appear. The RSTART special variable is set to the return value. The RLENGTH special variable is set to the length of the matched string, or to -1 (negative one) if no match is found.
$ awk 'BEGIN {
    str = "One Two Three"
    subs = "Two"

    ret = match(str, subs)

    printf "Substring \"%s\" found at %d location.\n", subs, ret
}'

The output result is:

Substring "Two" found at 5 location.
split( String, A, [Ere] ) Splits the argument specified by the String parameter into array elements A
$ awk 'BEGIN {
    str = "One,Two,Three,Four"

    split(str, arr, ",")

    print "Array contains following values"

    for (i in arr) {
        print arr[i]
    }
}'

The output result is:

Array contains following values
One
Two
Three
Four
tolower( String ) Returns the string specified by the String parameter, with each uppercase character changed to lowercase. The mapping of uppercase and lowercase is defined by the LC_CTYPE category of the current locale.
$ awk 'BEGIN {
    str = "HELLO, WORLD !!!"

    print "Lowercase string = " tolower(str)
}'

The output result is:

Lowercase string = hello, world !!!
toupper( String ) Returns the string specified by the String parameter, with each lowercase character changed to uppercase. The mapping of uppercase and lowercase is defined by the LC_CTYPE category of the current locale.
$ awk 'BEGIN {
    str = "hello, world !!!"

    print "Uppercase string = " toupper(str)
}'

The output result is:

Uppercase string = HELLO, WORLD !!!
sprintf(Format, Expr, Expr, . . . ) Formats the expression specified by the Expr parameter according to the printf subroutine format string specified by the Format parameter and returns the resulting string.
$ awk 'BEGIN {
    str = sprintf("%s", "Hello, World !!!")

    print str
}'

The output result is:

Hello, World !!!
strtonum(str) strtonum converts the string str to a numeric value. If the string starts with 0, it is treated as an octal number; if the string starts with 0x or 0X, it is treated as a hexadecimal number; otherwise, it is treated as a floating-point number.
$ awk 'BEGIN {
    print "十进制数 = " strtonum("123")
    print "八进制数 = " strtonum("0123")
    print "十六进制数 = " strtonum("0x123")
}'

The output result is:

十进制数 = 123
八进制数 = 83
十六进制数 = 291

Note:EreThe part can be a regular expression.

1. Usage of gsub and sub

$ awk 'BEGIN{info="this is a test2012test!";gsub(/[0-9]+/,"||",info);print info}'
this is a test||test!

2. Finding a string (using index)

A ternary operator is used:expression ? action1 : action2

$ awk 'BEGIN{info="this is a test2012test!";print index(info,"11111")?"ok":"no found";}'
no found
$ awk 'BEGIN{info="this is a test2012test!";print index(info,"is")?"ok":"no found";}'
ok
$ awk 'BEGIN{info="this is a test2012test!";print index(info,"test")?"ok":"no found";}'
ok

3. Regular expression matching search (using match)

$ awk 'BEGIN{info="this is a test2012test!";print match(info,/[0-9]+/)?"ok":"no found";}'
ok

4. Extracting a substring (using substr)

Starting from the 4th character, extract a string of length 10.

$ awk 'BEGIN{info="this is a test2012test!";print substr(info,4,10);}'
s is a tes

5. String splitting (using split)

$ awk 'BEGIN{info="this is a test";split(info,tA," ");print length(tA);for(k in tA){print k,tA[k];}}'
4
2 is
3 a
4 test
1 this

Split info; use spaces to split the info string into a dynamic array tA. Note that the awk for...in loop is an unordered loop. It does not go from array subscript 1...n, so special attention is needed when using it.

6. Formatting string output (using sprintf)

The format string consists of two parts: one part is normal characters, which will be output as is; the other part is format specifiers, starting with%followed by one or more specifier characters, used to determine the format of the output content. Special attention is needed that usingprintfdoes not add a newline by default, whileprintthe function by default adds after each line\na newline character.

Format specifier Description
%d Decimal signed integer
%u Decimal unsigned integer
%f Floating-point number
%s String
%c Single character
%p The value of a pointer
%e Floating-point number in exponential form
%x %X unsigned integer in hexadecimal representation
%o unsigned integer in octal representation
%g Automatically choose an appropriate representation
$ awk 'BEGIN{n1=124.113;n2=-1.224;n3=1.2345; printf("%.2f,%.2u,%.2g,%X,%o\n",n1,n2,n3,n1,n1);}'
124.11,4294967295,1.2,7C,174
$  awk 'BEGIN{n1=124.113;n2=-1.224;n3=1.2645; printf("%.2f,%.2u,%.2g,%X,%o\n",n1,n2,n3,n1,n1);}'
124.11,4294967295,1.3,7C,174

Note:Looking at the n3 output value above, you will find that a relatively intelligent feature when processing with printf is that it can round to the specified decimal places.

Time Functions

Function Name Description Example
mktime( YYYY MM DD HH MM SS[ DST]) Generate time format
$ awk 'BEGIN {
    print "Number of seconds since the Epoch = " mktime("2014 12 14 30 20 10")
}'

The output result is:

Number of seconds since the Epoch = 1418604610
strftime([format [, timestamp]]) Format time output, convert a timestamp to a time string
For specific formats, see the table below.
$ awk 'BEGIN {
    print strftime("Time = %m/%d/%Y %H:%M:%S", systime())
}'

The output result is:

Time = 12/14/2014 22:08:42
systime() Get the timestamp, returning the total number of seconds from January 1, 1970 to the current time (not counting leap years)
awk 'BEGIN{now=systime();print now}'

The output result is:

1343210982

strftime date and time format specifiers:

No. Description
%a Weekday abbreviation (Mon-Sun).
%A Full weekday name (Monday-Sunday).
%b Month abbreviation (Jan).
%B Full month name (January).
%c Local date and time.
%C The century part of the year, whose value is the year divided by 100.
%d Decimal date (01-31)
%D Equivalent to %m/%d/%y.
%e Date, padded with a space if it has only one digit.
%F Equivalent to %Y-%m-%d, which is also the ISO 8601 standard date format.
%g The year of the ISO8610 standard week modulo 100 (00-99). For example, January 1, 1993 belongs to the 53rd week of 1992. So although it is the 1st day of 1993, its ISO8601 standard week-based year is 1992. Similarly, although December 31, 1973 belongs to 1973, it belongs to the first week of 1994. Therefore, the ISO8610 standard week-based year for December 31, 1973 is 1974 rather than 1973.
%G Full year corresponding to the ISO week-numbering year.
%h Equivalent to %b.
%H Hour in 24-hour format as a decimal number (00-23)
%I Hour in 12-hour format as a decimal number (00-12)
%j Day of the year (001-366)
%m Month (01-12)
%M Minute (00-59)
%n Newline character (ASCII LF)
%p 12-hour format (AM/PM)
%r Time in 12-hour format (equivalent to %I:%M:%S %p).
%R Equivalent to %H:%M.
%S Second value of time (00-60)
%t Tab character (tab)
%T Equivalent to %H:%M:%S.
%u Day of the week as a number (1-7), 1 is Monday.
%U Week number of the year (Sunday as the first day of the week), 00-53
%V Week number of the year (Monday as the first day of the week), 01-53.
%w Day of the week as a number (0-6), 0 is Sunday.
%W Week number of the year as a decimal number (Monday as the first day of the week), 00-53.
%x Local date representation
%X Local time representation
%y Year modulo 100.
%Y Full year as a decimal number.
%z Time zone in the format +HHMM (for example, the format required for RFC 822 or RFC 1036 time headers)
%Z Time zone name or abbreviation, no output if the time zone cannot be determined.

Bitwise Functions

Function name Description Example
and Bitwise AND operation.
$ awk 'BEGIN {
    num1 = 10
    num2 = 6

    printf "(%d AND %d) = %d\n", num1, num2, and(num1, num2)
}'

The output is:

(10 AND 6) = 2
compl Bitwise complement.
$ awk 'BEGIN {
    num1 = 10

    printf "compl(%d) = %d\n", num1, compl(num1)
}'

The output is:

compl(10) = 9007199254740981
lshift Left shift operation
$ awk 'BEGIN {
    num1 = 10

    printf "lshift(%d) by 1 = %d\n", num1, lshift(num1, 1)
}'

The output is:

lshift(10) by 1 = 20
rshift Right shift operation
$ awk 'BEGIN {
    num1 = 10

    printf "rshift(%d) by 1 = %d\n", num1, rshift(num1, 1)
}'

The output is:

rshift(10) by 1 = 5
or Bitwise OR operation
$ awk 'BEGIN {
    num1 = 10
    num2 = 6

    printf "(%d OR %d) = %d\n", num1, num2, or(num1, num2)
}'

The output is:

(10 OR 6) = 14
xor Bitwise XOR operation
$ awk 'BEGIN {
    num1 = 10
    num2 = 6

    printf "(%d XOR %d) = %d\n", num1, num2, xor(num1, num2)
}'

The output is:

(10 bitwise xor 6) = 12

Other Functions

Function name Description Example
close(expr) Close a file or pipe
$ awk 'BEGIN {
    cmd = "tr [a-z] [A-Z]"
    print "hello, world !!!" |& cmd
    close(cmd, "to")
    cmd |& getline out
    print out;
    close(cmd);
}'

The output is:

HELLO, WORLD !!!
  • The first statement cmd = "tr [a-z] [A-Z]" establishes a two-way communication channel in AWK.
  • The second statement print provides input to the tr command. &| indicates two-way communication.
  • The third statement close(cmd, "to") closes the to process after execution is completed.
  • The fourth statement cmd |& getline out uses the getline function to store the output in the out variable.
  • The subsequent output statement prints the content of the output, and finally the close function closes cmd.
delete Used to delete an element from an array
$ awk 'BEGIN {
    arr[0] = "One"
    arr[1] = "Two"
    arr[2] = "Three"
    arr[3] = "Four"

    print "Array elements before delete operation:"
    for (i in arr) {
        print arr[i]
    }

    delete arr[0]
    delete arr[1]

    print "Array elements after delete operation:"
    for (i in arr) {
        print arr[i]
    }
}'

The output is:

Array elements before delete operation:
One
Two
Three
Four

Array elements after delete operation:
Three
Four
exit Terminates script execution; it can accept an optional argument expr to pass the AWK return status.
$ awk 'BEGIN {
    print "Hello, World !!!"

    exit 10

    print "AWK never executes this statement."
}'

The output is:

Hello, World !!!
flush Flush the buffer of an open file or pipe  
getline Read the next line

Use getline to read a line from the file marks.txt and output it:

$ awk '{getline; print $0}' marks.txt 

AWK reads a line from the file marks.txt and stores it in variable 0. In the next statement, we use getline to read the next line. Therefore AWK reads the second line and stores it in variable 0. Finally, AWK uses print to output the content of the second line. This process continues until the end of the file.

next Stop processing the current record and proceed to the processing of the next record.

When the pattern matches successfully, the program does not perform any operation:

$ awk '{if ($0 ~/Shyam/) next; print $0}' marks.txt
nextfile Stop processing the current file and start processing from the first record of the next file.

First create two files. The contents of file1.txt are as follows:

file1:str1
file1:str2
file1:str3
file1:str4

The contents of file2.txt are as follows:

file2:str1
file2:str2
file2:str3
file2:str4

Now let's test the nextfile function.

$ awk '{ if ($0 ~ /file1:str2/) nextfile; print $0 }' file1.txt file2.txt

The output is:

file1:str1
file2:str1
file2:str2
file2:str3
file2:str4
return Return a value from a user-defined function. Note that if no return value is specified, the return value is undefined.

Create a file functions.awk with the following content:

function addition(num1, num2)
{
    result = num1 + num2

    return result
}

BEGIN {
    res = addition(10, 20)
    print "10 + 20 = " res
}

Execute the file:

$ awk -f functions.awk 
10 + 20 = 30
system Execute a specific command and return its exit status. A return value of 0 indicates that the command executed successfully; a non-zero value indicates that the command failed.
$ awk 'BEGIN { ret = system("date"); print "Return value = " ret }'

The output is:

Sun Dec 21 23:16:07 IST 2014
Return value = 0