SoFunction
Updated on 2025-03-10

Common operations built into linux shell strings (get length, find, replace)

I have posted related articles before. Here, we recommend that you 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 perform various string operations. In fact, the shell has a series of operating symbols built-in to achieve similar effects. Using internal operators will omit the time to start external programs, so the speed will be very fast. If built-in operators can do it, use built-in first.

1 Read the string value

expression meaning
${var} The original value of the 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 and returns default, but does not change the value of var
${var=default} var does not declare that it returns default, and sets the value of var to default
${var:=default} var is not declared or its value is empty and returns default, 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 does not return other as empty, but does not change the value of var
${var?err_msg} var is not declared, send the message err_msg 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*} All variables declared before matching begin with varprefix
${!varprefix@} All variables declared before matching begin with varprefix

2 string operations

expression meaning
${#string} length of string
${string:position} In string, extract substrings from position position
${string:position:length} In string, extract the substring of length $length starting from position 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 substring that matches the longest substring
${string%substring} From the end of the variable string, delete the substring that matches the shortest substring
${string%%substring} From the end of the variable string, delete the substring that matches the longest substring
${string/substring/replacement} Use replacement, to replace the first matching substring
${string//substring/replacement} Use replacement, replace all matching substrings
${string/#substring/replacement} Assuming that the prefix of string matches substring, then replace the matching substring
${string/%substring/replacement} Assuming that the suffix of string matches substring, then replace the matching substring
 Description: "substring" can be a regular expression

Author: Heaven and Soul and Earth Evil