shell脚本关于字符串操作

字符串单引号和双引号的差别

单引号中间不能再次出现单引号,这就意味这单引号中间出现变量是无效的,直接点说,单引号中间无论出现什么都会原样输出。但是单引号字串中不能出现单独一个的单引号(对单引号使用转义符后也不行),但可成对出现,作为字符串拼接使用。双引号中间是可以出现变量的,而且双引号中间是可以进行字符转移的。直接上简单代码显示:

#!/bin/bash

where="CSDN"
val1='I am in $where'
val2='I am in '$where''
val3='I am in ${where}'

val4="I am in ${where}"
echo $val1
echo $val2
echo $val3
echo $val4

输出结果:
I am in $where
I am in CSDN
I am in ${where}
I am in CSDN

字符串截取以及查找

在字符的查找中,我使用的是expr函数,因此在这里我们格外注意的是,expr函数返回的字符串起始位置不是0,不是0,不是0,重要的事说三遍。比如“CSDN”,那么当你在查找S字符的时候,那么返回值是2,而不是1。但是,字符串截取却是以0开始的。比如string=“csdn” string=${string:1:2} 。。。string将是tr。代码如下:

#bin/bash

string="where I am is CSDN"
space_where=1
j=0
i=0
while (($space_where!=0)) 
do
        space_where=$(expr index "$string" " ")
        strend=${#string}
        if (($space_where == 0));then
                echo "$i"th   ${string:$j:$strend}
        else
                echo "$i"th   ${string:$j:$space_where-1}
        fi
        string=${string:$space_where:$strend}
        i=$[ i+1 ]
done

输入结果如下:
0th where
1th I
2th am
3th is
4th CSDN

猜你喜欢

转载自blog.csdn.net/qq_37146395/article/details/84197382