Shell脚本的学习笔记二:字符串

菜鸟教程提供的Shell在线编辑器

Shell 字符串

项目 功能
单引号 原样输出,变量无效。但可用成对单引号嵌套成对单引号输出变量
双引号 定义字符串中附带有变量的命令并且想将其解析后再输出的变量。

1. 单引号

#!/bin/bash
test='Try to do it.'
echo 'I say ${test}'        #**[代码1]**
#echo ' \' '                #使用转义字符会报错,**[代码2]**
echo 'I say '${test}''      #**[代码3]**

单引号字符串的限制:

  • 单引号里的任何字符都会原样输出,单引号字符串中的变量无效;[代码1]
  • 单引号字串中不能出现单独一个的单引号(对单引号使用转义符后也不行),但可成对出现,作为字符串拼接使用。[代码2]
  • 可用成对单引号嵌套成对单引号输出变量。[代码3]

结果如下:

I say ${test}            #**[代码1]**
I say Try to do it.      #**[代码3]**

2. 双引号

#!/bin/bash
test="Try to do it."
echo "I say ${test}"        #**[代码1]**
#echo " " "                #不使用转义字符会报错,**[代码2]**
echo "I say '${test}'  \"${test}\" "      #使用转义字符,**[代码3]**

双引号字符串的优点:

  • 双引号里可以有变量,将其解析后再输出。[代码1]
  • 双引号里可以出现转义字符。[代码2][代码3]
I say Try to do it.
I say 'Try to do it.'  "Try to do it."

3. 拼接字符串

#!/bin/bash
reader="Yogile"

#双引号
output1="This is "$reader" !"
output2="This is ${reader} !"
echo $output1  $output2
echo ""
#单引号
output3='This is '$reader' !'
output4='This is ${reader} !'
echo $output3  $output4
echo ""
#单双引号混合
echo $output1 $output3

输出结果为:

#双引号
This is Yogile ! This is Yogile !
#单引号
This is Yogile ! This is ${reader} !
#单双引号混合
This is Yogile ! This is Yogile !

4. 获取字符串长度

使用${#xxxx}(xxxx为变量名)输出字符串长度。

#!/bin/bash
reader="Yogile"
echo ${#reader}      #输出 6

5. 提取、查找子字符串

同高级语言一样,Shell申请内存也从0位开始,0位指第 1 个字符。
${string:position:length}在从位置position开始提取长度为length的子串

string="This is Yogile. "
echo ""
#提取字符串
echo ${string:1:5}          # 输出"his i"
echo ${string:12:4}        # 输出"le. ",[代码xx]---------?:15位为空格,有输出
echo ""
#查找子字符串
#查找字符 i 或 g 的位置(计算最先出现的字母)
echo `expr index "$string" ig`  #  ` 是反引号,而不是单引号 '

6. 主要字符串操作(长度,读取,替换)

格式 含义
${#string} $string的长度
${string:position} 从位置$position开始提取子串
${string:position:length} 在从位置$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

猜你喜欢

转载自www.cnblogs.com/Yogile/p/10558456.html
今日推荐