shell编程学习
- 变量的高级用法
- 变量替换
- 字符串处理
- 获取字符索引
- 获取子串长度
- 抽取字符串中的子串
- 案例测试
变量的高级用法
变量替换
##变量替换(贪婪,从前往后匹配,匹配到进行删除)
test1='I love you,you love me'
echo $test1
handletest1=${test1##*ov}
echo $handletest1
##变量替换(非贪婪,从前往后匹配,匹配到进行删除)
test2='I love you,you love me'
echo $test2
handletest2=${test2#*ov}
echo $handletest2
##变量替换(非贪婪,从后往前匹配,匹配到进行删除)
test3='I love you,you love me'
echo $test3
handletest2=${test3%ov*}
echo $handletest2##变量替换(贪婪,从后往前匹配,匹配到进行删除)
test3='I love you,you love me'
echo $test3
handletest2=${test3%%ov*}
echo $handletest2
handletest2=${test3/ov/ef}
handletest2=${test3//ov/ef}
字符串处理
[root@localhost ~]# var1="Hello world"
[root@localhost ~]# len=${#var1}
[root@localhost ~]# echo $len
11
[root@localhost ~]#
[root@localhost ~]# len=`expr length "$len"`
[root@localhost ~]# echo $len
2
[root@localhost ~]#
获取字符索引
[root@localhost ~]# var1="Quickstart is a app"
[root@localhost ~]# ind=`expr index "$var1" start`
[root@localhost ~]# echo $ind
6
[root@localhost ~]# ind=`expr index "$var1" uniq`
[root@localhost ~]# echo $ind
2
[root@localhost ~]# ind=`expr index "$var1" cniq`
[root@localhost ~]# echo $ind
3
[root@localhost ~]#
获取子串长度
[root@localhost ~]# var1="quicstart is a app"
[root@localhost ~]# sub_len=`expr match "$var1" app`
[root@localhost ~]# echo $sub_len
0
[root@localhost ~]# sub_len=`expr match "$var1" quic`
[root@localhost ~]# echo $sub_len
4
[root@localhost ~]# sub_len=`expr match "$var1" quic*`
[root@localhost ~]# echo $sub_len
4
抽取字符串中的子串
[root@localhost ~]# var1="kafka hadoop yarn mapreduce"
[root@localhost ~]# substr1=${var1:10}
[root@localhost ~]# echo $substr1
op yarn mapreduce
[root@localhost ~]# substr2=${var1:10:5}
[root@localhost ~]# echo $substr2
op ya
[root@localhost ~]# substr3=${var1:-5}
[root@localhost ~]# echo $substr3
kafka hadoop yarn mapreduce
[root@localhost ~]# substr5=`expr substr "$var1" 10 5`
[root@localhost ~]# echo $substr5
oop y
[root@localhost ~]# substr3=${var1: -5}
[root@localhost ~]# echo substr3
substr3
[root@localhost ~]# echo $substr3
educe
[root@localhost ~]# substr3=${var1: -5:4}
[root@localhost ~]# echo $substr3
educ
[root@localhost ~]#
案例测试
#!/bin/bashstring="Bigdata process framework is Hadoop,Hadoop is an open source project"function print_tips
{echo "***********************"echo "1.打印string长度"echo "2.删除字符串中的所有Hadoop"echo "3.替换第一个Hadoop为Mapreduce"echo "4.替换全部的Hadoop为Mapreduce"echo "***********************"
}function len_of_string
{echo "${#string}"
}function del_hadoop
{echo "${string//Hadoop/}"
}function rep_hadoop_first
{echo "${string/Hadoop/Mapreduce}"
}function rep_hadoop_all
{echo "${string//Hadoop/Mapreduce}"
}while true
doecho "【string=$string】"echoprint_tipsread -p "pls input your choice(1,2,3,4,q,Q):" choicecase $choice in1)len_of_string;;2)del_hadoop;;3)rep_hadoop_first;;4) rep_hadoop_all;;q|Q)exit;;*)echo "Error";;esac
done