Calculating the length of a string
${#string}
expr length "$string"
v1="i love you"
len=`expr length "$v1"`
echo len
Copy the code
Gets the position of a substring character in a string
expr index "$string""$subString"
v1="i love you"
v2="ou"
subIndex=`expr index "${v1}" "${v2}"`
echo $subIndex
# 4
Return the first character in the substring
Copy the code
Gets the length of the substring matched from scratch
expr match "$string" "$substr"
v1="i love you"
v2="ou"
v3="i love"
v4="i losadf"
v5="i lov.*"
subLen1=`expr match "$v1" "$v2"`
subLen2=`expr match "$v1" "$v3"`
subLen3=`expr match "$v1" "$v4"`
subLen4=`expr match "$v1" "$v5"`
echo $subLen1 $subLen2 $subLen3 $subLen4
0, 6, 0, 10
Copy the code
Extract substrings
# 0123456789
# iloveyou.
v1="iloveyou."
# start = at bit 0
echo ${v1:0}
# iloveyou.
# Start with the third
echo ${v1:3}
# veyou.
Note the space after the colon and count from -1 to the right
echo ${v1: -3}
# ou.
echo ${v1: -3:1}
# o
# Match from left
echo ${v1:(-3)}
# ou.
# Start with # 2
expr substr "$v1"2, 3,# lov
${} starts at 0
Copy the code
exercises
Given a string variable string= “You are an ugly boy! I ‘m a handsome boy!” Enter 1 to print the string length. 2. Enter 2 to delete ugly and change an to A. Type 3 to replace’m to “am”. 4. Type 4 to replace! For.
#! /bin/bash
string="You are an ugly boy! I'm a handsome boy!"
function print_tips
{
echo "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
echo "1. Enter 1 to print the length of the string.
echo "2. Type 2 to delete ugly and turn an into an"
echo "3. Enter 3 to replace'm with 'am'."
echo "4. Type 4 to replace! For."
echo "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
}
function len_of_string
{
echo "${#string}"
}
function del_ugly_and_change_an_to_a
{
str="${string/ ugly/}"
echo "${str/an/a}"
}
function replace_m_am
{
echo "${string//\'m/ am}"
}
function replace_exclamation_mark_to_dot
{
echo "${string//! /.}"
}
while true
do
echo "String ="${string}""
echo
print_tips
read -p "Please input your choice (1|2|3|4|q)" choice
case $choice in
1)
len_of_string
;;
2)
del_ugly_and_change_an_to_a
;;
3)
replace_m_am
;;
4)
replace_exclamation_mark_to_dot
;;
q|Q
exit
;;
*)
echo "Error, Input only in (1|2|3|4|q)"
;;
esac
done
Copy the code