Awk built-in functions: index, match, length
Awk’s built-in string processing function is the one we use most.
Today, we share with you: index, match, length
- index(s, t)
the position in s where the string t occurs, or 0 if it does not. - match(s, r)
the position in s where the regular expression r occurs, or 0 if it does not. - length(s)
the length of its argument taken as a string, number of elements in an array for an array argument, or length of $0 if no argument.
Syntax
awk 'pattern { action }'
Example
In the following example, we use the awk index function to return the position where the string t appears in the string s. if the string t does not appear in the string s, it returns 0.
➜ ~ awk 'BEGIN{str="linux command. linux is the best";position=index(str, "the");print position;}'
25

In the following example, we use the awk match function to return the position where the string t appears in the string s and the length of the character T. The variables RSTART and RLENGTH are set to the position and length of the matched string. If not found, the variable rstart is 0 and rlength is – 1;
➜ ~ awk 'BEGIN{str="linux command. linux is the best";match(str, "the");print RSTART, RLENGTH;}'
25 3

➜ ~ awk 'BEGIN{str="linux command. linux is the best";match(str, "th1e");print RSTART, RLENGTH;}'
0 -1

In the following example, we use the awk length function to return the string length.
➜ ~ awk 'BEGIN{str="linux command. linux is the best";len=length(str);print len;}'
32
