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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值