第十四章 切分文件名提取文件扩展名或提取文件名:%、%%和#、##

第十四章 切分文件名提取文件扩展名或提取文件名:%、%%和#、

作用

有些脚本要根据文件名进行各种处理,有时候需要保留文件名抛弃文件后缀,也有时候需要文件后缀不要文件名,这类提取文件部分的操作使用shell的内建功能就能实现。需要用到的几个操作符有:%、%%、#、##

实例

从右向左匹配:%和%%操作符的示例

[root@ceshi jinghao]# cat t.txt 
#!/bin/bash
file_name='test.text'
name=${file_name%.*}
echo file name is: $name

[root@ceshi jinghao]# /bin/sh t.txt 
file name is: test

# ${var%.*} 含义:从$var中删除位于%右侧的通配符字符串,通配符从右向左进行匹配。
#现在给name赋值,name=test.text,name通配符从右向左就会匹配到.text,所以从$var中删除匹配到的结果。
# % 属于非贪婪操作符,它是从右向左匹配最短结果;%%属于贪婪匹配,会从右向左匹配符合条件的最长字符串。

[root@ceshi jinghao]# cat t2.txt     
#!/bin/bash

file_name='test.text.bak.old.123'
name=${file_name%%.*}
echo file name is: $name
[root@ceshi jinghao]# /bin/sh t2.txt  #当使用%% 结果
file name is: test

[root@ceshi jinghao]# /bin/sh t2.txt  #当使用% 结果
file name is: test.text.bak.old

从左向右匹配:#和##操作符示例

#从左向右 最短匹配
[root@ceshi jinghao]# cat a.txt     
#!/bin/bash
file_name='test.text.bak.old.123'
name=${file_name#*.}
echo file name is: $name

[root@ceshi jinghao]# /bin/sh a.txt  #从左向右 最短匹配
file name is: text.bak.old.123

#从左向右 最长匹配
[root@ceshi jinghao]# cat a.txt     
#!/bin/bash
file_name='test.text.bak.old.123'
name=${file_name##*.}
echo file name is: $name

[root@ceshi jinghao]# /bin/sh a.txt  #从左向右 最长匹配
file name is: 123

示例2:定义变量 url="man.linuxde.net"

[root@ceshi jinghao]# url="man.linuxde.net" #定义变量
[root@ceshi jinghao]# echo ${url%.*}    #从右向左 最短匹配
man.linuxde
[root@ceshi jinghao]# echo ${url%%.*}   #从右向左 最长匹配
man
[root@ceshi jinghao]# echo ${url#*.}    #从左向右 最短匹配
linuxde.net
[root@ceshi jinghao]# echo ${url##*.}   #从左向右 最长匹配
net

猜你喜欢

转载自blog.51cto.com/506554897/2118605