1.变量替换和测试
(1)变量替换
例子1:删除
1
variable_1 = "I love you,do you love me?"
echo $varible_1
I love you,do you love me?//出现整个字符串
2
var1 = ${variable_1#*ov}
echo $var1
e you,do you love me? //匹配到最开头的ov字符串就返回,并删除之前所有字符
3
var2 = ${variable_1##*ov}
echo $var2
e me? //匹配到最后的ov字符,并返回,删除之前所有字符
4
var3 = ${variable_1%ov*}
echo $var3
I love you,do you l //从后往前,最先遇到ov就返回
5
var4 = ${variable_1%%ov*}
echo $var4
I l //从后往前,遇到最后一个ov才返回
总结:
variable_1 = "I love you,do you love me?"
var1 = ${variable_1#*ov}
var2 = ${variable_1##*ov}
var3 = ${variable_1%ov*}
var4 = ${variable_1%%ov*}
例子2:替换
var5 = ${PATH/bin/BIN} //把PATH中从头开始第一个小写的bin替换成大写的BIN
var6 = ${PATH//bin/BIN} //全部替换
(2)变量测试
不常用
2.字符串处理
(1)计算字符串长度
1.计算字符串长度
var1 = "Hello World"
len = ${#var1}
len = ‘expr length "$string"’
(2)获取子串在字符串中的索引位置
//获取字符索引位置
expr index "$string" substr
var1 = "quicstart is a app"
ind = ‘expr index "$var1" start’
echo $ind //输出6
sub_len = 'expr match "$var1" app'
echo $sub_len //输出0
sub_len = 'expr match "$var1" quic'
echo $sub_len //输出4,说明是从头开始匹配,从中间匹配不到
sub_len = 'expr match "$var1" quic.*'
echo $sub_len //18
sub_len = 'expr match "$var1" quicstart'
echo $sub_len //9
该方法不常用
(3)计算子串长度
(4)抽取子串
var = “kafka hadoop yarn mapreduce”
substr_1 = ${var1:10} //从第10个位置提取,提取到最后一个字符
echo $substr_1 //op yarn mapreduce
substr_2 = ${var1:10:5} //从0开始,从第10个字符往后5个
echo $substr_2 //op ya
substr_3 = ${var1: -5}
echo $substr_3 //educe
substr_4 = ${var1:(-5)}
echo $substr_4 //educe,与substr_3一致
substr_5 = ${var1: -5:2}
echo $substr_5 //ed
substr_6 = 'expr substr "$var1" 10 5' //与substr_2比较,此处从1开始数
echo $substr_6 //oop y
索引下标是从0开始数,expr是从1开始数!
3.命令替换
例一:获取所有用户名并输出
例二:根据系统时间计算今年或明年
echo “This is $(date +%Y) year”
echo "This is $(($(date +%Y) + 1)) year"
$() 命令替换,= ``
$(()) 整数运算,加减乘除
例三:根据系统时间获取今年还剩下多少星期,已经过了多少星期
date +%j
echo "This year have passed $(date +%j) days"
echo "This year have passed $(($(date +%j)/7)) weeks"
根据系统时间计算还有多长时间到新年
echo "There is $((365 - $(date +%j))) days before new year"
echo "There is $(((365 - $(date +%j))/7)) weeks before new year"
例四:判定nginx进程是否存在,若不存在就拉进该进程
ps -ef | grep nginx //查看nginx进程是否存在
ps -ef | grep nginx | wc -l //最后是字母l,wc -l 作用是查看前面生成的有几行
systemctl stop nginx //杀死Nginx
ps -ef | grep nginx | grep -v grep | wc -l