${#string}
expr length "$string"
v1="i love you"
len=`expr length "$v1"`
echo len
複製代碼
expr index "$string""$subString"
v1="i love you"
v2="ou"
subIndex=`expr index "${v1}" "${v2}"`
echo $subIndex
# 4
# 注意: 他實際上是找子串中每一個字符的其實位置,返回最前面的那個
複製代碼
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
複製代碼
# 0123456789
# iloveyou.
v1="iloveyou."
# 從第零位開=始
echo ${v1:0}
# iloveyou.
# 從第三位開始
echo ${v1:3}
# veyou.
# 從右邊開始匹配 倒數第三個開始 注意冒號後面有空格 從右邊-1開始數
echo ${v1: -3}
# ou.
echo ${v1: -3:1}
# o
# 從左邊開始匹配
echo ${v1:(-3)}
# ou.
# 從第2位開始 截取3個
expr substr "$v1" 2 3
# lov
# 注意expr 索引從1開始 ${}是從0開始
複製代碼
給定一個字符串變量 string=「You are an ugly boy! I'm a handsome boy!」
要求啓動腳本後 1.輸入1 打印字符串長度 2.輸入2 刪除ugly 把 an 變成 a 3.輸入3 替換 'm 爲 「 am」 . 4.輸入4 替換 ! 爲 .bash
#!/bin/bash
string="You are an ugly boy! I'm a handsome boy!"
function print_tips
{
echo "********************************"
echo "1.輸入1 打印字符串長度."
echo "2.輸入2 刪除ugly 把 an 變成 a"
echo "3.輸入3 替換 'm 爲 「 am」 ."
echo "4.輸入4 替換 ! 爲 ."
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
複製代碼