Transferred from: http://my.oschina.net/aiguozhe/blog/41557, and the content was verified and modified.
1. Take the length
str="abcd"expr length $str 4echo ${#str} 4
2. Find the location of the substring
It seems that only a single character is available.
str="ABC"expr"a" 1 expr "b" 2expr"x" 0expr"" 0
3. Select a substring
Str="abcdef"ExprSubstr"$str" 1 3# starting from the first position to take 3 characters, ABCExprSubstr"$str" 2 5# Starting from the second position, take 5 characters, BcdefExprSubstr"$str" 4 5# 5 characters starting from the fourth position, DefEcho${STR:2The string is extracted from the second position, BcdefEcho${STR:2:3} # Extracts 3 characters from the second position, BCDEcho${STR: (-6):5# # Fifth to the right to extract a string from the bottom, ABCDEEcho${STR: (-4):3# 3 characters to the right from the bottom fourth position, CDE
4. Intercepting strings
Str="ABBC,DEF,GHI,ABCJKL"Echo${str#a*C} # Output, def,ghi,abcjkl a pound sign (#) means to intercept the shortest match from the left (the ABBC string is removed here)Echo${str# #a *C} # Output JKL, two pound sign (# #) means to intercept the longest match from the left (the ABBC,DEF,GHI,ABC string is removed here)Echo${str#"A*c"} # Output ABBC,DEF,GHI,ABCJKL because STR does not have"A*c"Sub-stringEcho${str##"A*c"} # Output ABBC,DEF,GHI,ABCJKL similarlyEcho${str#*a*c*the shortest string of *a*c* is ABBC, so the output is truncated, def,ghi,abcjklEcho${str##*a*c*} # Empty, * The longest string is allEcho${str#d*f) # output ABBC,DEF,GHI,ABCJKL,Echo${str#*d*F} # output, GHI,ABCJKLEcho${STR%A*L} # Abbc,def,ghi A percent percent (%) means that the shortest match is intercepted from the rightEcho${STR%%B*L} # A two percent sign (% of) means that the longest match is intercepted from the rightEcho${STR%A*C} # ABBC,DEF,GHI,ABCJKL
5. String substitution
str="apple, tree, apple tree"echo ${str/apple/Apple} # replaces the first occurrence of Apple echo ${str//apple/apple} # Replace all Appleecho ${str/#apple/Apple} # If the string str starts with Apple, replace it with Apple echo ${str/%apple/apple} # If the string str ends with Apple, replace it with Apple
Bash Shell String manipulation