Linux字符串截取
字符串截取在写Shell脚本时很有用,这里有8种方法进行实现,请看~~
预设变量
1
| var=http://www.aaa.com/123.htm
|
方法一
#号截取,删除左边字符,保留右边字符
1 2 3 4 5
| [zhaoty@localhost ~]$ var=http://www.aaa.com/123.htm [zhaoty@localhost ~]$ [zhaoty@localhost ~]$ echo ${var#*//} www.aaa.com/123.htm
|
方法二
## 号截取,删除左边字符,保留右边字符
1 2 3 4 5
| [zhaoty@localhost ~]$ var=http://www.aaa.com/123.htm [zhaoty@localhost ~]$ [zhaoty@localhost ~]$ echo ${var##*/} 123.htm
|
方法三
%号截取,删除右边字符,保留左边字符
1 2 3 4 5
| [zhaoty@localhost ~]$ var=http://www.aaa.com/123.htm [zhaoty@localhost ~]$ [zhaoty@localhost ~]$ echo ${var%/*} http://www.aaa.com
|
方法四
%% 号截取,删除右边字符,保留左边字符
1 2 3 4 5
| [zhaoty@localhost ~]$ var=http://www.aaa.com/123.htm [zhaoty@localhost ~]$ [zhaoty@localhost ~]$ echo ${var%%/*} http:
|
方法五
从左边第几个字符开始,及字符的个数
1 2 3 4 5
| [zhaoty@localhost ~]$ var=http://www.aaa.com/123.htm [zhaoty@localhost ~]$ [zhaoty@localhost ~]$ echo ${var:0:5} http:
|
方法六
从左边第几个字符开始,一直到结束
1 2 3 4 5
| [zhaoty@localhost ~]$ var=http://www.aaa.com/123.htm [zhaoty@localhost ~]$ [zhaoty@localhost ~]$ echo ${var:7} www.aaa.com/123.htm
|
方法七
从右边第几个字符开始,及字符的个数
1 2 3 4 5
| [zhaoty@localhost ~]$ var=http://www.aaa.com/123.htm [zhaoty@localhost ~]$ [zhaoty@localhost ~]$ echo ${var:0-7:3} 123
|
方法八
从右边第几个字符开始,一直到结束
1 2 3 4 5 6
|
[zhaoty@localhost ~]$ var=http://www.aaa.com/123.htm [zhaoty@localhost ~]$ [zhaoty@localhost ~]$ echo ${var:0-7} 123.htm
|
蚂蚁🐜再小也是肉🥩!