Awk string functions (1)
The sub and gsub functions are used to find the longest and leftmost substring that can match the regular expression in the record, and replace the substring with the replacement string. If the target string is specified, find the longest and leftmost substring that can match the regular expression in the target string and replace the substring with the replacement string. If no target string is specified, search for the entire record.
Sub Function Format
Sub (Regular Expression, replacement string );
Sub (Regular Expression, replacement string, target string );
Example
$ Awk '{sub (/Mac/, "MacIntosh"); print} 'filename;
$ Awk '{sub (/Mac/, "MacIntosh", $1); print}' filename
Note:
1. When the regular expression Mac is matched for the first time in the record ($0), the Mac is replaced with the string MacIntosh. The sub function only replaces the first matched string in each row (see the gsub function used to replace multiple matches ).
2. When the regular expression Mac is matched for the first time in the recorded 1st fields ($1), the Mac is replaced with the string MacIntosh. The sub function only replaces the first matched string in the target string. The gsub function replaces the regular expression in the string globally, that is, all the regular expressions that appear in the record ($0.
Gsub Function Format
Gsub (Regular Expression, replacement string );
Gsub (Regular Expression, replacement string, target string );
Example
$ Awk '{gsub (/CA/, "California"); print}' filename
$ Awk '{gsub (/[Tt] om/, "Thomas", $1); print}' filename
Note:
1. Each regular expression CA found in the record ($0) is replaced with California.
2. Each regular expression Tom or tom found in the first field is replaced with Thomas.
The index function returns the position of the substring in the string for the first time. The offset is calculated from position 1.
Format
Index (string, substring)
Example
$ Awk '{print index ("hollow", "low")}' filename
4
Note: The returned number is the position where the substring low appears for the first time in the string hollow. The offset starts from 1.
The length function returns the number of characters in a string. If no parameter is specified, the length function returns the number of characters in the record.
Format
Length (string)
Length
Example
$ Awk '{print length ("hello")}' filename
5
The length function returns the number of characters in the string hello.