1. Extract according to the specified character
${varible#*string} cuts the string after the first string from left to right ${varible%string*} cut the string after the last string from right to left
str="abcdefghd123"
echo ${str##*d}
123
echo ${str#*d}
efghd123
echo ${str%%d*}
abc
echo ${str%d*}
abcdefgh
Copy the code
The extensions:
1) Do string deletion
${variable name # subString regular expression} is equipped with substring at the beginning of the string, and the expression matching is deleted.
${variable name % SUBString regular expression} is equipped with substring from the end of the string to delete matching expressions.
Note: ${STR ##*/} and ${STR %/*} are the easiest ways to get the file name and directory address, respectively.
str="/home/domi/study"
echo ${str}
/home/domi/study
echo ${str#/}
home/domi/study
echo ${str#*/}
home/domi/study
echo ${str##*/}
study
Copy the code
2) String replacement
${variable} / find/replace value a replace “/” said the first, replace all “/ /” said, when the lookup in the “/” please add the escape character ‘\ / “said.
echo ${str/\//\\}
\home/domi/study
echo ${str//\//\\}
\home\domi\study
Copy the code
2, extract the specified position, length of the string
${varible:n1:n2}: Truncated variable varible is a string of length n2 starting from n1.
echo ${str:2:2}
cd
echo ${str:2:1}
c
echo ${str:0:1}
a
echo ${str:0:2}
ab
Copy the code
${varible:n1-n3:n2}: Truncated variable varible is a string of length n2 starting from the back to the front of the calculation (n1-n3).
echo ${str:1-2:2}
3
echo ${str:1-3:2}
23
echo ${str:1-3:1}
2
Copy the code
3. Extract the string of the specified format
Such as access to suffix ls -l | the cut – d “.” -f2
Ls -l displays all file information, cut follows (.) To slice and extract the second column of data.
4. String length
echo ${#str}