Awk built-in functions: gsub, sub, substr

Awk’s built-in string processing function is the one we use most.

Today, we share with you: gsub, sub, substr

  • substr(s, m [, n])
    the n-character substring of s that begins at position m counted from 1.  If no n, use the rest of the string.
  • sub(r, t [, s])
    substitutes t for the first occurrence of the regular expression r in the string s.  If s is not given, $0 is used.
  • gsub(r, t [, s])
    same as sub except that all occurrences of the regular expression are replaced; sub and gsub return the number of replacements.

Syntax

awk 'pattern {  action }'

Example

In the following example, we use the awk sub built-in function to perform a substring replacement, which replaces the first substring with t. The third parameter is optional and defaults to $0.

➜  ~ awk 'BEGIN{ str="linux command"; sub("linux", "unix", str);print str; }'
unix command

➜  ~ awk 'BEGIN{ str="linux command. linux is the best"; sub("linux", "unix", str);print str; }'
unix command. linux is the best

In the following example, we use the awk substr function to return a substring of length n from the Nth character in the string.

➜  ~ awk 'BEGIN{ str="linux command"; subs=substr(str,1,5);print subs; }'
linux

In the following example, we use the awk gsub built-in function for global replacement. It replaces all substrings that appear with t.

➜  ~ awk 'BEGIN{ str="linux command. linux is the best"; gsub("linux", "unix", str);print str; }'

unix command. unix is the best

Add a Comment

Your email address will not be published.