After learning about powerful text flow processing commands such as SED and awk, the simple string processing often forgets a more efficient and concise method, which is the shell's built-in string processing.
1, the judgment and assignment of the string.
An expression |
meaning |
${var} |
Variable var, our usual $var is its abbreviation. |
|
|
${var-default} |
If Var is not declared, then use $default as its value * |
${var:-default} |
If Var is not declared, or its value is empty, then $default is used as its value * |
|
|
${var=default} |
If Var is not declared, then use $default as its value * |
${var:=default} |
If Var is not declared, or its value is empty, then $default is used as its value * |
|
|
${var+other} |
If Var is declared, then its value is $other, otherwise it is a null string |
${var:+other} |
If Var is set, then its value is $other, otherwise it will be a null string |
|
|
${var? ERR_MSG} |
If Var is not declared, print $err_msg * |
${var:? ERR_MSG} |
If Var is not set, then print $err_msg * |
|
|
${!varprefix*} |
Matches all previously declared variables beginning with Varprefix |
${[email protected]} |
Matches all previously declared variables beginning with Varprefix |
2. String manipulation
An expression |
meaning |
${#string} |
Length of $string |
|
|
${string:position} |
In $string, start extracting substrings from position $position |
${string:position:length} |
In $string, a substring of length $length is extracted starting from position $position |
|
|
${string#substring} |
Delete the substring of the shortest match $substring from the beginning of the variable $string |
${string# #substring} |
Delete the substring of the longest matching $substring from the beginning of the variable $string |
${string%substring} |
Delete the substring of the shortest match $substring from the end of the variable $string |
${string%%substring} |
Delete 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 instead of all matching $substring |
${string/#substring/replacement} |
If the $string prefix matches the $substring, then the $replacement is used instead of the matching $substring |
${string/%substring/replacement} |
If the $string suffix matches the $substring, then the $replacement is used instead of the matching $substring |
Of course, these are only for a single string of processing, but in the face of text processing, although you can use the loop to achieve the effect of SED, but the speed of the lack of advantage.
Common string processing (intercept, judge, replace) for SED and ask under Linux shell