[ Bash ] 字符串操作

https://www.cnblogs.com/yeungchie/

字符串长度

str="yeungchie"

echo ${#str}
# 9

提取字符串子串

根据索引

str="yeungchie"

echo ${str:3:4}    # 提取索引 3 和之后的 4 个字符
# ngch

echo ${str:5}     # 提取索引 5 和之后的字符
# chie

echo ${str::5}    # 提取索引 5 之前的字符
# yeung

根据匹配

echo ${str#*e}      # 第一个 e 之后的字符
# ungchie

echo ${str##*e}     # 最后一个 e 之后的字符
# 

echo ${str%e*}      # 倒数第一个 e 之前的字符
# yeungchi

echo ${str%%e*}     # 倒数最后一个 e 之前的字符
# y

echo ${str#*[ye]}   # 第一个 y 或者 e 之后的字符
# eungchie

字符串替换

str="YEUNGCHIE"

echo ${str/E/-}    # 单次替换
# Y-UNGCHIE

echo ${str//E/-}    # 多次替换
# Y-UNGCHI-

首字符大写

str="yeungchie"

echo ${str^}
# Yeungchie

所有字符大写

str="yeungchie"

echo ${str^^}
# YEUNGCHIE

首字符小写

str="YEUNGCHIE"

echo ${str,}
# yEUNGCHIE

所有字符小写

str="YEUNGCHIE"

echo ${str,,}
# yeungchie

跳过未定义的变量

str="YEUNGCHIE"

echo $name
# 

echo ${name-YEUNGCHIE}
# YEUNGCHIE

echo ${name-str}
# str

echo ${name-$str}
# YEUNGCHIE
posted @ 2023-08-14 20:42  YEUNGCHIE  阅读(74)  评论(2编辑  收藏  举报