
字符串常用操
- 拼接
直接拼接
echo "$str1$str2"
- 查找
- 运算符
[[ $str3 =~ $str1 ]]
- 通配符
[[ $str3 == *$str2 ]] #以str2结尾 [[ $str3 == $str1* ]] #以str1开头
case
case $str3 in HELLO) echo "cai" ;; H*O) echo "song" ;; *) echo "caisong" ;; esac
- 替换
#语法:${变量/查找/替换值} # 若查找字符前以'//'开头则全部替换 ${str1/$str2/$str3}
- 长度
echo ${#str}
- 切割
cut
echo $str|cut -d'-' -f2
IFS
#IFS指定分隔符 OIFS=$IFS;IFS='-';set -- $str; str1=$1;str2=$2;IFS=$OIFS;
- 截取
- 从头部截取指定字符
# 语法: ${varibale#*string} #截取第一个string后的字符 ${varible##*string} #截取最后一个string后的字符
- 从尾部截取指定字符
# 语法: ${varibale%string*} #截取第一个string后的字符 ${varible%%string*} #截取最后一个string后的字符
示例
#!/bin/bash
lyric1="Soft kitty, warm kitty, little ball of fur"
lyric2="Happy kitty, sleepy kitty, purr, purr, purr"
echo -e $lyric1
echo -e $lyric2
echo -e "示例:拼接"
echo -e \\t "$lyric1 $lyric2"
echo -e "示例:查找"
echo -e "\t 1. 包含"
[[ $lyric1 =~ "kitty" ]] && echo -e "\t The lyric include kitty"
echo -e "2. 以字符串开头"
[[ $lyric1 == Soft* ]] && echo -e "\t The lyric starts with 'Soft'"
echo -e "3. 以字符串结尾"
[[ $lyric2 == *purr ]] && echo -e \\t "The lyric ends with 'purr'"
echo -e "4. 使用case查找"
case $lyric1 in
*ball)
echo -e "\tThe lyric include ball" ;;
sleepy*)
echo -e "\tThe lyric include sleepy" ;;
*kitty*)
echo -e "\tThe lyric include kitty" ;;
esac
echo -e "示例:替换"
echo -e \\t ${lyric1/kitty/doraemon}
echo -e \\t ${lyric1//kitty/doraemon}
echo -e "示例:长度"
echo -e "\tThe length of lryic is $((${#lyric1}+${#lyric2}))"
echo -e "示例:切割"
echo -e "\tcut命令切割"
echo -e $lyric1 | cut -d',' -f1
echo -e "\tIFS切割"
OIFS=$IFS;IFS=',';set -- $lyric2;cat1=$1;cat2=$2;IFS=$OIFS
echo -e "\tThe two cats:" $cat1 $cat2
echo -e "示例:截取"
echo -e "1. 从开头截取最少匹配"
echo -e \\t ${lyric1#*kitty}
echo -e "2. 从开头截取最多匹配"
echo -e \\t ${lyric1##*kitty}
echo -e "1. 从结尾截取最少匹配"
echo -e \\t ${lyric2%kitty*}
echo -e "2. 从结尾截取最多匹配"
echo -e \\t ${lyric2%%kitty*}
输出
Soft kitty, warm kitty, little ball of fur
Happy kitty, sleepy kitty, purr, purr, purr
示例:拼接
Soft kitty, warm kitty, little ball of fur Happy kitty, sleepy kitty, purr, purr, purr
示例:查找
1. 包含
The lyric include kitty
2. 以字符串开头
The lyric starts with 'Soft'
3. 以字符串结尾
The lyric ends with 'purr'
4. 使用case查找
The lyric include kitty
示例:替换
Soft doraemon, warm kitty, little ball of fur
Soft doraemon, warm doraemon, little ball of fur
示例:长度
The length of lryic is 85
示例:切割
cut命令切割
Soft kitty
IFS切割
The two cats: Happy kitty sleepy kitty
示例:截取
1. 从开头截取最少匹配
, warm kitty, little ball of fur
2. 从开头截取最多匹配
, little ball of fur
1. 从结尾截取最少匹配
Happy kitty, sleepy
2. 从结尾截取最多匹配
Happy