本文是Linux Shell脚本系列教程的第(五)篇,更多shell教程请看:Linux Shell脚本系列教程

字符串是Shell编程中最常用最有用的数据类型,继上一篇之后,今天,Linux大学网就为大家介绍一下在Shell中的字符串用法,以及Shell中常用的字符串操作。

Shell字符串用法

Shell中的字符串可以用引号包起来,也可以不用引号。

用引号的话可以用双引号,也可以用单引号。其单双引号的区别跟PHP相类似。

接下来给大家介绍下Shell中字符串单双引号的区别和用法举例。

加单引号

用法示例



str='justcode.ikeepstudying.com'



 

加单引号的特点:

  • Shell单引号里的任何字符都会被原样输出,单引号字符串中的变量无效;
  • Shell单引号字串中不能出现单引号(对单引号使用转义符也不行)。

加双引号

 

用法示例



myweb='justcode.ikeepstudying.com'
str="Hello, you are browsing \"$myweb\"! \n"



 

加双引号的优点:

  • Shell双引号里可以有变量
  • Shell双引号里可以出现转义字符

所以,建议大家在使用Shell时,对字符串要加上引号,而且最好加双引号。

Shell字符串的操作

Shell中对于字符串的操作如下表格所示:

表达式

含义

${#string}

$string的长度

${string:position}

在$string中, 从位置$position开始提取子串

${string:position:length}

在$string中, 从位置$position开始提取长度为$length的子串

${string#substring}

从变量$string的开头, 删除最短匹配$substring的子串

${string##substring}

从变量$string的开头, 删除最长匹配$substring的子串

${string%substring}

从变量$string的结尾, 删除最短匹配$substring的子串

${string%%substring}

从变量$string的结尾, 删除最长匹配$substring的子串

${string/substring/replacement}

使用$replacement, 来代替第一个匹配的$substring

${string//substring/replacement}

使用$replacement, 代替所有匹配的$substring

${string/#substring/replacement}

如果$string的前缀匹配$substring, 那么就用$replacement来代替匹配到的$substring

${string/%substring/replacement}

如果$string的后缀匹配$substring, 那么就用$replacement来代替匹配到的$substring

Linux Shell常用操作举例

接下来给大家举几个常用操作的例子

1)输出字符串长度



[justcode@ikeepstudying ~]$ test='I love china'
[justcode@ikeepstudying ~]$ echo ${#test}
12



 ${#变量名} 得到字符串长度

2)截取字符串



[justcode@ikeepstudying ~]$ test='I love china'
[justcode@ikeepstudying ~]$ echo ${test:5}    
e china
[justcode@ikeepstudying ~]$ echo ${test:5:10}
e china



 ${变量名:起始:长度}得到子字符串

3)字符串的删除



[justcode@ikeepstudying ~]$ test='c:/windows/boot.ini'
[justcode@ikeepstudying ~]$ echo ${test#/}
c:/windows/boot.ini
[justcode@ikeepstudying ~]$ echo ${test#*/}
windows/boot.ini
[justcode@ikeepstudying ~]$ echo ${test##*/}
boot.ini

[justcode@ikeepstudying ~]$ echo ${test%/*}
c:/windows
[justcode@ikeepstudying ~]$ echo ${test%%/*}


 ${变量名#substring正则表达式}从字符串开头开始配备substring,删除匹配上的表达式。

${变量名%substring正则表达式}从字符串结尾开始配备substring,删除匹配上的表达式。

注意:${test##*/},${test%/*} 分别是得到文件名,或者目录地址最简单方法。

4)字符串的替换



[justcode@ikeepstudying~]$ test='c:/windows/boot.ini'
[justcode@ikeepstudying~]$ echo ${test/\//\\}
c:\windows/boot.ini
[justcode@ikeepstudying~]$ echo ${test//\//\\}
c:\windows\boot.ini



 ${变量/查找/替换值} 一个“/”表示替换第一个,”//”表示替换所有,当查找中出现了:”/”请加转义符”\/”表示。

好了,以上就是Shell字符串的一些基本概念和常用命令,希望大家能够熟练掌握。

更多shell教程请看:Linux Shell脚本系列教程