【Shell】字符串

单引号和双引号

shell 字符串可以用单引号 '',也可以用双引号 “”,也可以不用引号。

  • 单引号的特点
    • 单引号里不识别变量
    • 单引号里不能出现单独的单引号(使用转义符也不行),但可成对出现,作为字符串拼接使用。
  • 双引号的特点
    • 双引号里识别变量
    • 双引号里可以出现转义字符

综上,推荐使用双引号。

拼接字符串

# 使用单引号拼接
name1='white'
str1='hello, '${name1}''
str2='hello, ${name1}'
echo ${str1}_${str2}
# Output:
# hello, white_hello, ${name1}

# 使用双引号拼接
name2="black"
str3="hello, "${name2}""
str4="hello, ${name2}"
echo ${str3}_${str4}
# Output:
# hello, black_hello, black

获取字符串长度

text="hello"
echo ${#text}
# Output:
# 5

截取子字符串

从第 3 个字符开始,截取 2 个字符

text="hello"
echo ${text:2:2}
# Output:
# ll

查找子字符串

查找 ll 子字符在 hello 字符串中的起始位置。

text="hello"
echo `expr index "${text}" ll`

# Output:
# 3

本文作者:Hello、Lin

本文链接:https://www.cnblogs.com/HelloWxl/p/17352807.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Hello、Lin  阅读(54)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.