The cloud-dwelling community has also made relevant articles before. Here, we recommend that you use some of the built-in functions.
String-related operations are often involved when writing a shell program. There are many command statements, such as awk,sed, that can do all kinds of string operations. In fact, the shell built a series of operating symbols, to achieve similar effects, the use of internal operators will omit the launch of external programs and other time, so the speed will be very fast. If the built-in operators are able to do this, use the built-in first.
1 Reading String values
An expression |
Meaning |
${var} |
Variable var original value |
${var-default} |
VAR does not declare return default, but does not change the value of Var |
${var:-default} |
VAR returns default without declaring or its value is null, but does not change the value of Var |
${var=default} |
VAR does not declare return default and sets the value of Var to default |
${var:=default} |
VAR returns default without declaring or its value is null, and sets the value of Var to default |
${var+other} |
VAR is declared to return other but does not change the value of Var |
${var:+other} |
VAR is declared and not NULL to return other, but does not change the value of Var |
${VAR?ERR_MSG} |
VAR is not declared, sending message err_msg to standard error output |
${VAR:?ERR_MSG} |
VAR is not declared or empty, sending message err_msg to standard error output |
${!varprefix*} |
Match all variables previously declared with the Varprefix start |
${!varprefix@} |
Match all variables previously declared with the Varprefix start |
2 string manipulation
An expression |
Meaning |
${#string} |
Length of string |
${string:position} |
In string, the substring is extracted from the position position |
${string:position:length} |
In string, a substring of length $length is extracted starting at position position |
${string#substring} |
Deletes the substring of the shortest matching substring from the beginning of the variable string |
${string# #substring} |
Deletes the substring of the longest matching substring from the beginning of the variable string |
${string%substring} |
Deletes the substring of the shortest matching substring from the end of the variable string |
${string%%substring} |
Deletes the substring of the longest matching substring from the end of the variable string |
${string/substring/replacement} |
Use replacement to replace the first matching substring |
${string//substring/replacement} |
Use replacement to replace all matching substring |
${string/#substring/replacement} |
Assuming the prefix of string matches substring, the replacement is substituted for the substring |
${string/%substring/replacement} |
Assuming the suffix of string matches substring, the replacement is substituted for the substring |
Description: "substring" can be a regular expression |
Author: Desun of the Heavenly Soul