linux学习记录—变量的高级用法
程序员文章站
2022-07-01 23:52:53
...
1、删除字符串
variable_1="I love you, Do you love me"
echo $variable_1
从前面开始匹配,删除最短的,结果"e you, Do you love me"
var1=${variable_1#*ov}
从前面开始匹配,删除最长的,结果"e me"
var2=${variable_1##*ov}
从后面开始匹配,删除最短的,结果"I love you, Do you l"
var3=${variable_1%ov*}
从后面开始匹配,删除最长的,结果"I l"
var4=${variable_1%%ov*}
2、替换字符串
将变量PATH里的第一个bin替换成BIN
var5=${PATH/bin/BIN}
将变量PATH里的所有bin替换成BIN
var5=${PATH//bin/BIN}
3、获取字符串长度及查找
${#string}
expr length $string
expr index $string $substring
var1="hello world"
获取字符串长度
len=${#var1}
len=`expr length "$var1"`
获取字符位置,按每个字符查找
ind=`expr index "$var1" hello`
ind=`expr index "$var1" hbiu` #找得到,因为有h
获取子串长度,只能从头开始匹配
sub_len=`expr match "$var1" hello`
sub_len=`expr match "$var1" world` //找不到
4、截串
下标从0开始
${string:position}
${string:position:length}
#${string: -position:length}或者${string:(positioin)}
var1="hello world"
substr1=${var1:5}
substr1=${var1:4:3}
#substr1=${var1:-1:3}
substr1=${var1:(-1)}
下标从1开始
expr substr $string position length
substr1=`expr substr "$var1" 4 6`
5、命令替换
`command`或$(command)
//以:为分隔符,获取第一个元素
cat passwd | cut -d ":" -f 1
index=1
for user in `cat passwd | cut -d ":" -f 1`; do
echo "This is $index user: $user"
index=$[$index + 1]
#index=$(($index + 1))
done
6、date相关
date +%Y //年份
echo "This is $(date +%Y) year"
echo "This is $(($(date +%Y) + 1))" //$(())做运算
man date //查看命令信息
date +%j //day of year
echo "This year has passed $(date +%j) days"
echo "This year has passed $((10#$(date +%j) / 7)) weeks" //10#转换成十进制
echo "This year has $(((365-10#$(date +%j)) / 7)) weeks left"
7、声明变量类型
declare typeset
declare -r var2="hello" //-r readonly
var2="world"
num1=10
num2=$num1+20 //默认字符串,输出10+20
expr $num1+20 //默认字符串,输出10+20
declare -i num3 //-i integer
num3=$num1+90
declare -f
declare -F
declare -a array
array=("hello" "world" "joker" "rich")
echo ${array[@]} //打印数组内容
echo ${array[0]} //打印下标为0的内容
echo ${#arrsy[@]} //打印数组长度
声明环境变量
declare -x num5
删除变量的声明
declare +r
declare +i
declare +a
declare +x
8、expr的使用
expr $num1 operator $num2 #注意空格
或$(($num1 operator $num2 ))
或$[$num1 -lt $num2]
expr $num1 \> $num2
read -p "please input a positive number: " num
expr $num + 1 &> /dev/null
if [ $? -ne 0]; then
exit -1
fi
if [ `expr $num \> 0` -ne 0]; then
exit -1
fi
for ((i=1; i<=$num; i++)); do
sum=`expr $sum + $i`
done
echo "1+2+3...+$num=$sum"
9、bc的使用
which bc
bc
scale=2 //两位小数位
10+10.2
echo "23+35" | bc
echo "23.3+35" | bc
echo "scale=4;23.3/35" | bc
read -p "num1: " num1
read -p "num2: " num2
result=`echo "scale=4;$num1/$num2" | bc`
echo $result
上一篇: 自动采集程序