Handling strings in shell scripts
1, ${#变量名}
Function: Returns the length of a string
# foo= "This is a test"
# echo ${#foo}//Returns the length of the string foo
14
2. ${variable name: offset:length}
Function: Intercepts the string, length specifies the Intercept, or does not write; The index value of the first character of the string is 0
# foo= "ABCDEFG"
# echo ${foo:3:2}//from the Subscript 3 character start intercept, 2 total interception
De
# echo ${foo:3}//Start capturing the last character from the character subscript 3
Defg
3. ${variable name #pattern} ${variable name # #parttern}
Pattern: mode, wildcard expression
Function: Clears pattern-matching characters in a string
# foo= "File.txt.zip"
# echo ${foo#*.} A # symbol is cleared according to the shortest match
Txt.zip
# echo ${foo##*.} The 2 # symbol is cleared according to the longest match
Zip
4. ${variable name%pattern} ${variable name%%parttern}
Pattern: mode, wildcard expression
Function: Clears the pattern-matching character from the string and matches the string last
# echo $foo
File.txt.zip
# echo ${foo%.*}//1% stands according to shortest match
File.txt
# echo ${foo%%.*}//2-percent percent is represented by the longest match
File
5. String substitution operation
${variable name/old/new}
[Email protected] ~]# foo= "Mp3.txt.txt.mp3.avi"
[Email protected] ~]#
[[email protected] ~]# echo ${foo/txt/txt}
MP3. TXT.txt.mp3.avi
[Email protected] ~]#
[[email protected] ~]# echo ${foo//txt/txt}
MP3. Txt. TXT.mp3.avi
[Email protected] ~]# foo= "Txt.mp3.txt"
[Email protected] ~]#
[[email protected] ~]# echo ${foo/#txt/txt}
TXT.mp3.txt
[[email protected] ~]# echo ${foo/%txt/txt}
Txt.mp3.TXT
6, to achieve the conversion of uppercase and lowercase letters
# foo= "Abde"
# echo ${foo,,}//Convert string foo all to lowercase
Abde
# echo ${foo,}//Convert the 1th character of the string foo to lowercase
Abde
# echo ${foo^}//Converts the 1th character of a string foo to uppercase
Abde
# echo ${foo^^}//Convert string foo all to uppercase
Abde
This article is from the "lyw666" blog, make sure to keep this source http://lyw666.blog.51cto.com/12823216/1957420
Handling of shell strings