2013年3月22日 星期五 晴
变量扩展:取字符串切片
一、定义变量
[root@desktop7 ~]# Name=Simth_Jacob
[root@desktop7 ~]#
[root@desktop7 ~]# Name2=(Cheng Long)
[root@desktop7 ~]#
二、取值
1、数组取值(查看数组成员)
[root@desktop7 ~]# echo ${Name2[1]}
Long
[root@desktop7 ~]#
[root@desktop7 ~]# echo ${Name2[0]}
Cheng
[root@desktop7 ~]#
2、变量切片取值
(1)截取变量值第三个字符到最后
[root@desktop7 ~]# echo ${Name:2}
mth_Jacob
[root@desktop7 ~]#
(2)截取变量值第六个字符到最后
[root@desktop7 ~]# echo ${Name:5}
_Jacob
(3)截取变量值从第三个到第五个字符
[root@desktop7 ~]# echo ${Name:2:4}
mth_
[root@desktop7 ~]#
三、变量扩展
查看变量
[root@desktop7 ~]# echo $PATH
/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/root/bin
1、删除第一个 ${variable#key}
[root@desktop7 ~]# echo ${PATH#*:}
/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/root/bin
2、删除条件冒号(:)前所有 ${variable##key}
[root@desktop7 ~]# echo ${PATH##*:}
/root/bin
3、删除最后一个 ${variable%key}
[root@desktop7 ~]# echo ${PATH%:*}
/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin
4、删除条件冒号(:)后所有 ${variable%%key}
[root@desktop7 ~]# echo ${PATH%%:*}
/usr/kerberos/sbin
5、旧内容换为新内容,替换首个 ${variable/old/}
[root@desktop7 ~]# echo ${PATH/sbin/QQ}
/usr/kerberos/QQ:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/root/bin
6、旧内容换为新内容,替换首个 ${variable//old/}
[root@desktop7 ~]# echo ${PATH//usr/QQ}
/QQ/kerberos/sbin:/QQ/kerberos/bin:/QQ/local/sbin:/QQ/local/bin:/sbin:/bin:/QQ/sbin:/QQ/bin:/QQ/X11R6/bin:/root/bin
7、小练习
[root@desktop7 ~]# echo 999|sed 's9\9\9\99669'
66
[root@desktop7 ~]# echo 999|sed 's9\9\9\99\9\9\9\9\9\99'
999999
[root@desktop7 ~]# echo 999|sed 's#999#999999#'
999999
替换字符可随意,可用转义字符转义原含义,如数字、字母等
[root@desktop7 ~]# echo 999|sed 'sa999a999999a'
999999
[root@desktop7 ~]# echo 999|sed 'ss999s999999s'
999999
[root@desktop7 ~]# echo 999|sed 'ss99s88899s'
888999
[root@desktop7 ~]# echo 999|sed 'ss9s88899s'
8889999
[root@desktop7 ~]# echo 989|sed 'ss9s88899s' #默认替换首个
8889989
[root@desktop7 ~]# echo 999|sed 's;99;88899;'
888999
转载于:https://blog.51cto.com/fengzhao001/1160362