脚本进阶之字符串处理

字符串处理

1、获取字符串长度

[root@linux1 ~]# string='hello world'
[root@linux1 ~]# echo ${#string}
11
[root@linux1 ~]# echo ${string}
hello world

2、字符串切片

格式:

${parameter:offset}
${parameter:offset:length}
截取从 offset 个字符开始,向后 length 个字符。

[root@linux1 ~]# string='hello world'
#截取hello
[root@linux1 ~]# echo ${string:0:5}
hello
#截取wo
[root@linux1 ~]# echo ${string:6:2}
wo
#截取world
[root@linux1 ~]# echo ${string:5}
world
#截取最后一个字符
[root@linux1 ~]# echo ${string:(-1)}
d
#截取最后两个字符
[root@linux1 ~]# echo ${string:(-2)}
ld
#截取从倒数第三个字符后的2个字符
[root@linux1 ~]# echo ${string:(-3):2}
rl

3、替换字符串

格式:${parameter/pattern/string}

[root@linux1 ~]# string='hello world world.'
#将第一个word替换为WORLD
[root@linux1 ~]# echo ${string/world/WORLD}
hello WORLD world.
#将所有world替换为WORLD
[root@linux1 ~]# echo ${string//world/WORLD}
hello WORLD WORLD.

#替换正则匹配为空,使用了正则表达式
[root@linux1 ~]# string=abc123
#将所有非数字字符替换为空
[root@linux1 ~]# echo ${string//[^0-9]/}
123
#替换所有数字字符为空
[root@linux1 ~]# echo ${string//[0-9]/}
abc

4、字符串截取

格式:

${parameter#word} # 删除匹配前缀
${parameter##word}
${parameter%word} # 删除匹配后缀
${parameter%%word}

# 去掉左边,最短匹配模式,##最长匹配模式。

% 去掉右边,最短匹配模式,%%最长匹配模式。

示例:

好记一点:#删左边,所以*放分隔符左边

%删右边,所有*放分隔符右边

[root@linux1 ~]# URL="https://www.ithome.com/0/441/491.htm"
#以//为分隔符,删除左边留下右边
[root@linux1 ~]# echo ${URL##*//}
www.ithome.com/0/441/491.htm
#以/作为分隔符,删除左边,留下右边
[root@linux1 ~]# echo ${URL##*/}
491.htm
#以:为分隔符,删除右边,留下左边
[root@linux1 ~]# echo ${URL%%:*}
https
#以/为分隔符,删除右边,留下左边
[root@linux1 ~]# echo ${URL%/*}
https://www.ithome.com/0/441
#以点为分隔符,删除左边留下,右边
[root@linux1 ~]# echo ${URL##*.}
htm

5、变量状态赋值

${VAR:-string} 如果 VAR 变量为空则返回 string
${VAR:+string} 如果 VAR 变量不为空则返回 string
${VAR:=string} 如果 VAR 变量为空则重新赋值 VAR 变量值为 string
${VAR:?string} 如果 VAR 变量为空则将 string 输出到 stderr

脚本进阶之字符串处理

如果变量为空就返回 hello world!:
# VAR=
# echo ${VAR:-'hello world!'}
hello world!
如果变量不为空就返回 hello world!:
# VAR="hello"
# echo ${VAR:+'hello world!'}
hello world!
如果变量为空就重新赋值:
# VAR=
# echo ${VAR:=hello}
hello
# echo $VAR
hello
如果变量为空就将信息输出 stderr:
# VAR=
# echo ${VAR:?value is null}
-bash: VAR: value is null

6、变量颜色

字体颜色字体背景颜色显示方式
30:黑<br/>31:红<br/>32:绿<br/>33:黄<br/>34:蓝色<br/>35:紫色<br/>36:深绿<br/>37:白色40:黑<br/>41:深红<br/>42:绿<br/>43:黄<br/>44:蓝色<br/>45:紫色<br/>46:深绿<br/>47:白色0:终端默认设置<br/>1:高亮显示<br/>4:下划线<br/>5:闪烁<br/>7:反白显示<br/>8:隐藏

格式:

\033[1;31;40m       # 1 是显示方式,可选。31 是字体颜色。40m 是字体背景颜色。
\033[0m             # 恢复终端默认颜色,即取消颜色设置。

7、字符大小写转换

[root@linux1 ~]# string=abc123ABC
[root@linux1 ~]# echo ${string}
abc123ABC
#转换成大写
[root@linux1 ~]# echo ${string^^}
ABC123ABC
#转换成小写
[root@linux1 ~]# echo ${string,,}
abc123abc
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值