Shell编程系列 https://www.jianshu.com/nb/37140890
计算字符串长度
- ${#string}
- expr length "$string"
v1="i love you"
len=`expr length "$v1"`
echo len
获取子串中字符在字符串中的位置
- expr index "subString"
v1="i love you"
v2="ou"
subIndex=`expr index "${v1}" "${v2}"`
echo $subIndex
# 4
# 注意: 他其实是找子串中每个字符的其实位置,返回最前面的那个
获取子串从头开始匹配的长度
- expr match "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 替换 ! 为 .
#!/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
网友评论