Site icon LinuxCommands.site

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

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

Exit mobile version