研究过几次linux 里的 BASH_SOURCE 了,一直搞不明白${BASH_SOURCE-$0}
是什么意思。感觉来学习一下linux 中的 bash 里头自带的字符串操作。
一、字符串长度
语法:
${#string}
用途:
返回字符串的长度。
示例:
root@FENG:/mnt/h/tmp/tmp# a=djklgjdklsjdlkgsjlk
root@FENG:/mnt/h/tmp/tmp# echo ${#a}
19
root@FENG:/mnt/h/tmp/tmp# date
Sun Aug 27 16:43:06 CST 2023
二、字符串截取
语法:
${string:position:length}
- position: 子串的起始位置
- length: 字串的长度,可省略
用途:
返回指定的字串
示例
root@FENG:/mnt/h/tmp/tmp# a=dgkjsnwienlsfd
root@FENG:/mnt/h/tmp/tmp# echo ${a:3}
jsnwienlsfd
root@FENG:/mnt/h/tmp/tmp# echo ${a:3:3}
jsn
root@FENG:/mnt/h/tmp/tmp# date
Sun Aug 27 16:50:41 CST 2023
三、删除子串
语法:
${string#sustring}
用途:
删除正向匹配到的子串,
注意:最短匹配规则时是单个#
,最长匹配时是两个##
示例:
root@FENG:/mnt/h/tmp/tmp# a=abcABCdjskgdjABC
root@FENG:/mnt/h/tmp/tmp# echo ${a#a*A}
BCdjskgdjABC
root@FENG:/mnt/h/tmp/tmp# echo ${a##a*A}
BC
root@FENG:/mnt/h/tmp/tmp# date
Sun Aug 27 16:56:45 CST 2023
语法:
${string%substring}
用途
删除反向匹配的子串
示例
root@FENG:/mnt/h/tmp/tmp# a=abcABCdjskgdjABC
root@FENG:/mnt/h/tmp/tmp# echo ${a%A*C}
abcABCdjskgdj
root@FENG:/mnt/h/tmp/tmp# echo ${a%%A*C}
abc
root@FENG:/mnt/h/tmp/tmp# date
Sun Aug 27 16:58:51 CST 2023
四、字符串替换
语法:
${string/substring/replacement}
用途
替换第一个匹配到的子串
示例
root@FENG:/mnt/h/tmp/tmp# a=abctesttestABC
root@FENG:/mnt/h/tmp/tmp# echo ${a/test/qijing}
abcqijingtestABC
root@FENG:/mnt/h/tmp/tmp#
root@FENG:/mnt/h/tmp/tmp# date
Sun Aug 27 17:01:04 CST 2023
语法:
${string//substring/replacement}
用途
替换所有匹配到的子串
示例
root@FENG:/mnt/h/tmp/tmp# a=abctesttestABC
root@FENG:/mnt/h/tmp/tmp# echo ${a//test/qijing}
abcqijingqijingABC
root@FENG:/mnt/h/tmp/tmp#
root@FENG:/mnt/h/tmp/tmp# date
Sun Aug 27 17:01:04 CST 2023
网友评论