使用shell扩展匹配文件名
目标
通过使用Bash shell的模式匹配功能,高效地运行影响很多文件的命令。
名词定义
使用命令行拓展
Bash shell有多种扩展命令行的方式,包括模式匹配、主目录扩展、字符串扩展和变量替换。启中最强大的或许是路径名称匹配功能,在过去被称为通配。Bash通配功能常称为“通配符”,可以使管理大量文件边的更加轻松。使用扩展的元字符来匹配要寻找的文件名和路径名,可以一次性针对集中的一组文件执行命令。模式匹配
通配是一种shell命令解析操作,它将一个通配符模式拓展到一组匹配的路径名。在执行命令之前,命令行元字符有匹配列表替换。不返回匹配项的模式,将原始模式请求显示为字面上的文本。下列为常见的元字符和模式类。
- 元字符和匹配项表
| 模式 | 匹配项 |
|---|---|
| * | 有零个或更多字符组成的任何字符串 |
| ? | 任何一个字符 |
| [abc…] | 括起的类(位于两个方括号之间)中的任何一个字符 |
| [!abc…] | 不在括起的类中的任何一个字符 |
| [^abc…] | 不在括起的类中的任何一个字符 |
| [[:alpha:]] | 任何字母字符 |
| [[:lower:]] | 任何小写字符 |
| [[:upper:]] | 任何大写字符 |
| [[:alnum:]] | 任何字母字符或数字 |
| [[:punct:]] | 除空格和字母数字以外的任何可打印字符 |
| [[:digit:]] | 从0到9的任何单个数字 |
| [[:space:]] | 任何一个空白字符。这可能包括制表符、换行符、回车符、换页符或空格 |
实操演示
[root@jenkins ~]# touch aaa abd adc dd den sec adb acf
[root@jenkins ~]# ll
总用量 8
-rw-r--r-- 1 root root 0 1月 28 15:48 aaa
-rw-r--r-- 1 root root 0 1月 28 15:48 abd
-rw-r--r-- 1 root root 0 1月 28 15:48 acf
-rw-r--r-- 1 root root 0 1月 28 15:48 adb
-rw-r--r-- 1 root root 0 1月 28 15:48 adc
-rw-------. 1 root root 2007 7月 22 2021 anaconda-ks.cfg
-rw-r--r-- 1 root root 0 1月 28 15:48 dd
-rw-r--r-- 1 root root 0 1月 28 15:48 den
-rw-r--r--. 1 root root 2038 7月 22 2021 initial-setup-ks.cfg
-rw-r--r-- 1 root root 0 1月 28 15:48 sec
##创建演示文件
[root@jenkins ~]# ls a*
aaa abd acf adb adc anaconda-ks.cfg
##匹配a开头的
[root@jenkins ~]# ls a??
aaa abd acf adb adc
##匹配a开头的后面任意内容的文件
[root@jenkins ~]# ls [ads]*
aaa abd acf adb adc anaconda-ks.cfg dd den sec
##匹配ads字母开头的文件
[root@jenkins ~]# ls [!ds]*
aaa acf adc initial-setup-ks.cfg
abd adb anaconda-ks.cfg
[root@jenkins ~]# ls *a*
aaa acf adc initial-setup-ks.cfg
abd adb anaconda-ks.cfg
##匹配中间包含a字母的文件
[root@jenkins ~]# ls ~
aaa adc initial-setup-ks.cfg 视频 音乐
abd anaconda-ks.cfg sec 图片 桌面
acf dd 公共 文档
adb den 模板 下载
[root@jenkins ~]# ls ~sinfotek
##查看用户的家目录
[root@jenkins ~]# echo {1..5}
1 2 3 4 5
[root@jenkins ~]# echo {1..5}{a..f}
1a 1b 1c 1d 1e 1f 2a 2b 2c 2d 2e 2f 3a 3b 3c 3d 3e 3f 4a 4b 4c 4d 4e 4f 5a 5b 5c 5d 5e 5f
##大括号扩展
[root@jenkins ~]# echo $HOSTNAME
jenkins
##应用变量
[root@jenkins ~]# echo \$HOSTNAME
$HOSTNAME
##反斜杠转义字符
[root@jenkins ~]# echo 'my gistbane is $HOSTNAME'
my gistbane is $HOSTNAME
##单引号
[root@jenkins ~]# echo "my gistbane is $HOSTNAME"
my gistbane is jenkins
##双引号
[root@jenkins ~]# echo `hostname`
jenkins
##反引号
[root@jenkins ~]# echo ${HOSTNAME}_$USER
jenkins_root
##输出多个变量
文档更新时间: 2022-01-28 16:11 作者:xiubao yan