Linux shell string built-in Common Operations (get length, search, replace), linuxshell
String-related operations are often involved when writing shell programs. There are many command statements, suchAwk, sedCan perform various string operations. In fact, shell has a series of built-in operation symbols to achieve similar results. Using Internal operators will omit the time such as starting external programs, so the speed will be very fast. If the built-in operators can do this, the built-in operators are preferred.
1. deduce the string value to be read.
Expression |
Description |
$ {Var} |
Original Value of the variable var |
$ {Var-default} |
Var does not declare that default is returned, but the value of var is not changed. |
$ {Var:-default} |
If var is not declared or its value is null, default is returned, but the value of var is not changed. |
$ {Var = default} |
Var does not declare that default is returned, and the value of var is set to default. |
$ {Var: = default} |
If var is not declared or its value is null, default is returned, and the value of var is set to default. |
$ {Var + other} |
Var is declared to return other, but the value of var is not changed |
$ {Var: + other} |
If var is declared and not empty, other is returned, but the value of var is not changed. |
$ {Var? Err_msg} |
Var is not declared. The message err_msg is sent to the standard error output. |
$ {Var :? Err_msg} |
Var is not declared or empty. Send the message err_msg to the standard error output. |
$ {! Varprefix *} |
Match all variables declared starting with varprefix |
$ {! Varprefix @} |
Match all variables declared starting with varprefix |
2 string operations
Expression |
Description |
$ {# String} |
String Length |
$ {String: position} |
In string, extract the substring from position |
$ {String: position: length} |
In string, extract the substring with the length of $ length from the position |
$ {String # substring} |
From the beginning of the variable string, delete the substring that matches the shortest substring. |
$ {String ## substring} |
From the beginning of the variable string, delete the substrings that match the longest substring. |
$ {String % substring} |
From the end of the string variable, delete the substring that matches the shortest substring. |
$ {String % substring} |
From the end of the string variable, delete the substring that matches the longest substring. |
$ {String/substring/replacement} |
Replacement is used to replace the first matched substring. |
$ {String // substring/replacement} |
Replacement is used to replace all matched substrings. |
$ {String/# substring/replacement} |
Assume that the string prefix matches the substring, replacement is used to replace the matched substring. |
$ {String/% substring/replacement} |
Assume that the string suffix matches the substring, replacement is used to replace the matched substring. |
Note: "substring" can be a regular expression. |