1. Length
[Email protected] ~]$ test= ' I love China '
[Email protected] ~]$ echo ${#test}
12
${#变量名} to get the string length
2. Intercept strings
[Email protected] ~]$ test= ' I love China '
[[email protected] ~]$ echo ${test:5}
E China
[[email protected] ~]$ echo ${test:5:10}
E China
${variable Name: start: length} get substring
3. String deletion
[Email protected] ~]$ test= ' C:/windows/boot.ini '
[[email protected] ~]$ echo ${test#/}
C:/windows/boot.ini
[[email protected] ~]$ echo ${test#*/}
Windows/boot.ini
[[email protected] ~]$ echo ${test##*/}
Boot. ini
[[email protected] ~]$ echo ${test%/*}
C:/windows
[[email protected] ~]$ echo ${test%%/*}
${variable name #substring regular expression} starts with substring from the beginning of the string and deletes the expression on the match.
${variable name%substring regular expression} starts with substring from the end of the string and deletes the expression on the match.
Note: ${test##*/},${test%/*} is the simplest way to get the file name, or directory address, respectively.
4. String substitution
[Email protected] ~]$ test= ' C:/windows/boot.ini '
[[email protected] ~]$ echo ${test/\//\\}
C:\windows/boot.ini
[[email protected] ~]$ echo ${test//\//\\}
C:\windows\boot.ini
${variable/find/Replace value} A "/" means replacing the first, "//" means replacing all, when the lookup appears: "/" Please add escape character "/" to indicate.
In the shell, through awk,sed,expr and so on can be implemented, the string above operation. Below we perform a performance comparison.
[Email protected] ~]$ test= ' C:/windows/boot.ini '
[[Email protected] ~]$ time for I in $ (seq 10000);d o a=${#test};d one;
Real 0m0.173s
User 0m0.139s
SYS 0m0.004s
[[Email protected] ~]$ time for I in $ (seq 10000);d o a=$ (length of expr $test);d one;
Real 0m9.734s
User 0m1.628s
The speed difference is hundreds of times, call external command processing, and built-in operator performance is very different. In shell programming, try to complete with built-in operators or functions. Similar results can occur with awk,sed.