Shell入门(三)之字符串

一、单引号

字符串可以用单引号,也可以用双引号,也可以不用引号。单双引号的区别跟PHP类似。

单引号不存在转义字符,如:\a,\n,$abc

#!/bin/bash
a='abc'
b='${a}bc';
echo $b;       #结果为:${a}bc

单引号字符串的限制:

(1)单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的;

(2)单引号字串中不能出现单引号(对单引号使用转义符后也不行)。

 

二、双引号

双引号的优点:

(1)双引号里可以有变量

(2)双引号里可以出现转义字符

#!/bin/bash
a="abc"
b="${a}bc";
echo $b;       #结果为:$abcbc

 

三、字符串连接

#!/bin/bash
a="abc"
b=$a"d"
c=$b'e'
echo $a $b $c

 

四、字符串长度

${#string}获取长度

`expr length 字符串`   字符串可以加'或" ,其中"适用于所有字符,包括转义字符,变量

 注意使用的是反引号 ` 而不是单引号 '

#!/bin/bash
a='abc'
echo ${#a}     #3
echo `expr length "字符串"`  #9  中文占3个字节

 

五、提取子字符串

${string:start}     从字符串第 start 个字符开始截取到字符串末尾,下标从0开始

${string:start:length}  从字符串第 start 个字符开始截取 length个字符,下标从0开始

${string:0-start}     从字符串倒数第 start 个字符开始截取到字符串末尾

${string:0-start:length}  从字符串倒数第 start 个字符向右开始截取 length个字符

 

`expr substr 字符串 start  length`  下标从1开始,字符串可以加'或" ,其中"适用于所有字符,包括转义字符,变量

#!/bin/bash
a='abcdefg'
echo ${a:2}      #cdefg
echo ${a:2:2}    #cd
echo ${a:0-1}    #g
echo ${a:0-5:4}  #cdef
echo `expr substr "$a" 1  2`    #ab

 

六、在字符串查找字符

下标从1开始,查找不到返回0

`expr index 字符串 匹配字符`

 

字符串与匹配字符都可以加'或" ,其中"适用于所有字符,包括转义字符,变量

#!/bin/bash
a='welcome to learn shell'
echo `expr index "$a" co`                              #4
b='b'
echo `expr index b字符串 匹配字符`                      #2
echo `expr index "b字符串" '匹配字符'`           #2
echo `expr index "b字符串" "${b}匹配字符"`         #1

 

七、正则匹配

`expr match 字符串 匹配字符串`     匹配字符串开头的子串,返回匹配到的子串的长度,若找不到则返回0

字符串与匹配字符串都可以加'或" ,其中"适用于所有字符,包括转义字符,变量

#!/bin/bash
a='welcome to learn shell'
echo `expr match "$a" w.*a`     #14
echo `expr match "$a" e.*a`     #0  尽管字符串包含e.*a,但不以w开头    

 

八、删除  支持通配符*与?、+等

${string#删除子串}     删除左边最小的匹配string开头的子串

${string##删除子串}   删除左边最大的匹配string开头的子串

${string%删除子串}     删除右边最小的匹配string末尾的子串

${string%%删除子串}   删除右边最大的匹配string末尾的子串

#!/bin/bash
a='welcome to learn shell'
echo  ${a#e*e}      #welcome to learn shell   没有匹配$a的开头
echo  ${a#w*e}      #lcome to learn shell
echo  ${a##w*e}     #ll                   
echo  ${a%e*l}      #welcome to learn sh
echo  ${a%%e*l}     #w

 

九、替换  支持通配符*与?、+等

${string/被替换串/替换串}

${string//被替换串/替换串}

#!/bin/bash
a='welcome on welcome'
echo  ${a/e*c/x}       #wxome
echo  ${a/e*c/x}       #wxome
echo  ${a//el/a}       #wacome on wacome

 

posted @ 2017-08-23 16:28  茅坤宝骏氹  阅读(220)  评论(0编辑  收藏  举报