Awk built-in functions: split, tolower, toupper, sprintf

Today we will share four commonly used awk built-in string functions:

  • split(String, A, [Ere])
    Splits the parameter specified by the String parameter into the array elements A[1], A[2], . . ., A[n], and returns the value of the n variable. This separation can be done with the extended regular expression specified by the Ere parameter, or with the current field separator (FS special variable) (if no Ere parameter is given)
  • tolower( String )
    Returns the string specified by the String parameter, each uppercase character in the string will be changed to lowercase
  • toupper( String )
    Returns the string specified by the String parameter, each lowercase character in the string will be changed to uppercase
  • sprintf( Format, 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.

Syntax

awk 'pattern {  action }'

Example

In the following example, we use the awk split function to split the string str into an array according to the fixed delimiter “,”, and print the third item of the array.

awk 'BEGIN { 
    str = "a b c d";
    split(str, arr, " ");
    print arr[3];
}'

In the following example, we use the awk tolower function to convert all strings to lowercase.

awk 'BEGIN { 
    str = "Linux Command Site!";
    newStr = tolower(str);
    print newStr;
}'

In the following example, we use the awk toupper function to convert all strings to uppercase.

awk 'BEGIN { 
    str = "Linux Command Site!";
    newStr = toupper(str);
    print newStr;
}'

In the following example, we use the awk sprintf function to convert the string according to the format.

awk 'BEGIN { 
    str = "%s Command Site!";
    newStr = sprintf(str, "Linux");
    print newStr;
}'

Add a Comment

Your email address will not be published. Required fields are marked *