Common operations built in Linux shell string (get length, find, replace)

Time:2021-10-15

Developeppaer has also posted relevant articles before. Here, we recommend you to use some built-in functions.

When writing shell programs, string related operations are often involved. There are many command statements, such as awk and sed, which can do various string operations. In fact, the shell has a series of built-in operation symbols, which can achieve similar effects. The use of internal operation symbols will omit the time to start external programs, so the speed will be very fast. If the built-in operator can do it, the built-in operator is preferred.

1 read string value

expression meaning
${var} Value of variable var
${var-default} Var does not declare to return default, but does not change the value of var
${var:-default} VaR is not declared or its value is empty. It returns default, but does not change the value of var
${var=default} Var does not declare to return default, and sets the value of VaR to default
${var:=default} VaR is not declared or its value is empty, return default, and set 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 is not empty, return other, but do not change the value of var
${var?err_msg} VaR is not declared, the message err_ MSG sent to standard error output
${var:?err_msg} VaR is not declared or empty, and the message err_ MSG sent to standard error output
${!varprefix*} Matches all variables previously declared starting with varprefix
${[email protected]} Matches all variables previously declared starting with varprefix

2 string operation

expression meaning
${#string} Length of string
${string:position} In the string, the substring is extracted from the position
${string:position:length} In string, extract a substring with a length of $length from position
${string#substring} Delete the substring with the shortest matching substring from the beginning of variable string
${string##substring} Delete the longest substring matching substring from the beginning of variable string
${string%substring} Delete the substring with the shortest matching substring from the end of the variable string
${string%%substring} Delete the longest substring matching substring from the end of variable string
${string/substring/replacement} Use replacement to replace the first matching substring
${string//substring/replacement} Use replacement to replace all matching substrings
${string/#substring/replacement} Assuming that the prefix of a string matches a substring, replace the matching substring with a replacement
${string/%substring/replacement} Assuming that the suffix of a string matches a substring, replace it with a replacement
 Note: “substring” can be a regular expression

Author: Tian Hun Di Sha