Shell之变量子串与变量替换
一、变量子串操作表
表达式 | 说明 |
${#string} | 返回$string的长度 |
${string:position} | 在$string中,从位置$position之后开始提取子串 |
${string:position:length} | 在$string中,从位置$position之后开始提取长度为$length的子串 |
${string#substring} | 从变量$string开头开始删除最短匹配$substring子串 |
${string##substring} | 从变量$string开头开始删除最长匹配$substring子串 |
${string%substring} | 从变量$string结尾开始删除最短匹配$substring子串 |
${string%%substring} | 从变量$string结尾开始删除最长匹配$substring子串 |
${string/substring/replace} | 使用$replace来代替第一个匹配的$substring |
${string/#substring/replace} | 如果$string前缀匹配$substring,就用$replace来代替$substring |
${string/%substring/replace} | 如果$string后缀匹配$substring,就用$replace来代替$substring |
二、变量子串操作
(一)简单操作
1、${#string}
[root@localhost ~]# name="bright" [root@localhost ~]# echo ${#name} 6
2、${string:position}
[root@localhost ~]# echo ${name:2} ight
3、${string:position:length}
[root@localhost ~]# echo ${name:2:2} ig
4、${string#substring}
[root@localhost ~]# name="bright" [root@localhost ~]# echo ${name#br} ight
5、${string##substring}
[root@localhost ~]# name="brightbright" [root@localhost ~]# echo ${name##b*r} ight
6、${string/substring/replace}
[root@localhost ~]# echo ${name/ht/wn} brigwn
7、${string/#substring/replace}
[root@localhost ~]# name="bright" [root@localhost ~]# echo ${name/#br/wn} wnight
8、${string/%substring/replace}
[root@localhost ~]# name="bright" [root@localhost ~]# echo ${name/%ht/wn} brigwn
(二)应用场景
上面是简单的用法,在生产场景中,可用子串操作处理文件名等,如:
[root@localhost StringOperation]# ls -l total 0 -rw-r--r-- 1 root root 0 Jan 16 22:38 1_fi.txt -rw-r--r-- 1 root root 0 Jan 16 22:38 2_fi.txt -rw-r--r-- 1 root root 0 Jan 16 22:38 3_fi.txt
将上面文件名中的fi去掉。
#!/bin/sh for file in `ls ./*.txt` do /bin/mv $file `echo "${file%fi*}.txt"` done
处理后的结果为:
[root@localhost StringOperation]# ls -l total 4 -rw-r--r-- 1 root root 0 Jan 16 22:38 1_.txt -rw-r--r-- 1 root root 0 Jan 16 22:38 2_.txt -rw-r--r-- 1 root root 0 Jan 16 22:38 3_.txt
三、变量替换表
表达式 | 说明 |
${value:-word} |
如果变量名存在且非null,则返回变量的值;否则,返回word字符串。 用途:变量未定义,则返回默认值。 |
${value:=word} |
如果变量名存在且非null,则返回变量的值;否则,设置变量值为word并返回。 用途:变量未定义,设置默认值并返回。 |
${value:?"not defined"} | 用于捕捉变量未定义而导致的错误,并退出程序。 |
${value:+word} | 测试变量是否存在,如果已经定义返回word |
更多详情可通过man bash命令查看。
四、变量替换操作
1、${value:-word}
# 变量未定义 [root@localhost ~]# echo ${name:-default} default #变量内容为空 [root@localhost ~]# name="" [root@localhost ~]# echo ${name:-default} default
#判断变量是否定义
2、${value:=word}
#变量未定义 [root@localhost ~]# echo ${name:=default} default #变量值为空 [root@localhost ~]# name="" [root@localhost ~]# echo $name [root@localhost ~]# echo ${name:=default} default
#取保变量始终有值
3、 ${value:?"not defined"}
root@localhost ~]# unset name [root@localhost ~]# echo ${name:?"not defined"} -bash: name: not defined
#捕捉变量未定义引起的错误
4、 ${value:+word}
# 测试变量是否已经定义,如果没有定义无返回值 [root@localhost ~]# name="bright" [root@localhost ~]# echo ${name:+1} 1
作者:iveBoy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。