/** Reference address of this article: * /// Note: If I use ubuntu11.4 and run shell script sh test, an error is returned. Run/bin/bash test to obtain the correct result.
String Truncation in Shell
STR = "abc123abcabc"
# Calculate the length of a string
Echo $ {# STR} #12
# Operations related to location parameters
Echo $ {# *} # Number of location parameters
Echo $ {## the number of location parameters is the same as the above
Echo $ * # output all location parameters as a string
Echo $ @ # same effect as above
# String Truncation
#
# $ {String # substring}
# Remove the first matched $ substring from the first character on the left of $ string
#$ {String ## substring}
# Remove the last matched $ substring from the first character on the left of $ string
#
# Start from the left
Echo $ {STR # A * c} # minimum matching between A and C
Echo $ {STR # A * c} # maximum matching between A and C
# Start from the right
Echo $ {STR % A * c} # Start from the last character on the right to find the shortest match between A and B.
Echo $ {STR % a * B} # Find the longest match between A and B starting from the last character on the right
# The mode cannot be found.
#== Substring =
# $ {String: Position}
# $ {String: positon: length}
#
Echo $ {STR: 2} # extract the string value from the first position
Echo $ {STR: 2: 3} # extract a value with a length of 3 characters from the first position
# Reverse extraction of substrings
Echo $ {STR :(-2)} # extract the string from the first position in the reverse direction
Echo $ {STR :(-2): 6} # extract a string with a length of 6 characters from the reverse of 2nd characters (:( it is impossible)
# How to extract 6 characters with only two characters in length?
Echo $ {STR :(-6): 3} #6 medium proposed 3 Total can be
# Location Parameter Extraction
Echo $ {*: 2} # extract the values of all the following parameters from the second parameter
Echo $ {*: 2: 3} # extract the values of the three parameters from the second parameter
# = Substring replacement =
# $ {String/substring/replacement}
# Use $ replacement to replace the first matched $ substring.
# $ {String // substring/replacement}
# Use $ replacement to replace all matched $ substring.
#
# $ {String/# substring/replacement}
# If $ substring matches the starting part of $ string, replace $ substring with $ replacement.
# $ {String/% substring/replacement}
# If $ substring matches the end of $ string, replace $ substring with $ replacement.
#
Str1 = "123abcabcab12"
Echo $ {str1/12/hover} # Replace the first
Echo ${str1 // 12/hover} # Replace all
Echo $ {str1/#12/hover} # Match 12 from the beginning. If yes, replace
Echo $ {str1/% 12/hover} # Match 12 from the end. If it is found, replace