字符串截取

指定字符内容截取

a*c 匹配开头为a,中间人任意个字符,结尾为c的字符串
  • 删除匹配到的字符串
[root@localhost shell]# name2=abcABcabc
[root@localhost shell]# echo ${name2}
abcABcabc
# #号从开头匹配到最小的a到c并删除
[root@localhost shell]# echo ${name2#a*c}
ABcabc
# ##号从左侧还是匹配,匹配最长的a到b,并删除
[root@localhost shell]# echo ${name2##a*b}
c

[root@localhost shell]# echo ${name2}
abcABcabc
# %号从右侧开始匹配,删除最短的a到c
[root@localhost shell]# echo ${name2%a*c}
abcABc
# %%号从右侧开始匹配,删除最长的a到c
[root@localhost shell]# echo ${name2%%a*c}

  • 替换字符串
[root@localhost shell]# echo ${name2}
wo shi da sb
# / 匹配到第一个并进行替换
[root@localhost shell]# echo ${name2/sb/SB}
wo shi da SB

[root@localhost shell]# echo ${name2}
wo wo tou
# // 匹配到所有的并进行替换
[root@localhost shell]# echo ${name2//wo/WO}
WO WO tou

替换文件名的案例

# 创建文件
[root@localhost cahnge_more_file]# touch chaochao_{1..5}_finished.jpg
[root@localhost cahnge_more_file]# touch chaochao_{1..5}_finished.png
[root@localhost cahnge_more_file]# ls
chaochao_1_finished.jpg  chaochao_2_finished.jpg  chaochao_3_finished.jpg  chaochao_4_finished.jpg
chaochao_5_finished.jpg
chaochao_1_finished.png  chaochao_2_finished.png  chaochao_3_finished.png  chaochao_4_finished.png chaochao_5_finished.png
 
# 使用 mv 可以改名,单个文件
name=chaochao_1_finished.jpg
mv name `echo ${name//_finished/}`

# 找出需要的文件 文件名包含finished的jpg文件
[root@localhost cahnge_more_file]# ls *_finished*.jpg
chaochao_1_finished.jpg  chaochao_2_finished.jpg  chaochao_3_finished.jpg  chaochao_4_finished.jpg chaochao_5_finished.jpg

# 使用for批量循环
[root@localhost cahnge_more_file]# for i in `ls *_finished*.jpg`;do echo ${i};done
chaochao_1_finished.jpg
chaochao_2_finished.jpg
chaochao_3_finished.jpg
chaochao_4_finished.jpg
chaochao_5_finished.jpg

# 使用for循环,字符串echo ${i//_finished/}进行替换
[root@localhost cahnge_more_file]# for i in `ls *_finished*.jpg`;do mv ${i} `echo ${i//_finished/}`;done
posted @ 2022-05-07 10:10  savagee  阅读(32)  评论(0)    收藏  举报