一、什么是元字符?

  • 元字符(Meta Character)是指键盘上可输入的对于Shell来说具有其他特殊含义的字符被称为元字符,不同的Shell元字符不一定相同。 简单的讲就是元字符:一些有特殊意义的字符,可以替代其他的字符。

  • 作用:简化字符串、模糊匹配

二、常用元字符

2.1、"~"

  • 代表的是家目录

2.2、"*"

  • 匹配0或者若干个任意字符 举例:
[root@localhost ~]# cd
[root@localhost ~]# mkdir test
[root@localhost ~]# cd test
[root@localhost ~]# touch a.txt b.txt ab.txt ab abc a bc

查询test目录以a开头的文件?
[root@localhost ~]# ls a*
查询test目录以txt为后缀的文件?
[root@localhost ~]# ls *.txt
删除以b开头的文件?
[root@localhost ~]# rm b*

2.3、"?"

  • 匹配单个字符(有且只匹配一个字符) 举例:
- 查询test目录第二个字符为b的文件?
[root@localhost ~]# ls ?b*
- 查询test目录以a开头的文件,文件名的长度是3字符?    
[root@localhost ~]# ls a??

2.4、"[]"

  • 从一组字符中匹配单个字符 举例:
[root@localhost ~]# touch  link1.txt   link2.txt   n.txt    k.txt
[root@localhost ~]# ls *[link]*.txt    
[root@localhost ~]# ls *link*.txt
[root@localhost ~]# ls [b-fB-F]*.txt

2.5、";"

  • 连接多个命令(多个命令互不相干) 举例:
[root@localhost ~]# cd /;ls
[root@localhost ~]# date;cal;pwd

date:显示时间
cal:显示当前月的日历
cal 4 2023:显示2023年4月的日历
cal 2023:显示2023年的日历

2.6、"|"

  • 管道连接符(前一个命令的输出作为后一个命令的输入) 举例:
[root@localhost ~]# ls -l /etc | more
[root@localhost ~]# more /etc/passwd
  • 注意:more:分屏显示内容,一次性显示一屏幕

2.7、">,>>,<"

  • 1)>:重定向输出到文件,覆盖文件的内容。
[root@localhost ~]# cal 4 2023 > test.txt
[root@localhost ~]# cal 10 2023 > test.txt
  • 2)>>:重定向输出到文件,追加文件的内容。
[root@localhost ~]# cal 7 2023 >> test.txt
  • 3)<:重定向输入到文件 cat:默认输入是键盘 举例:
[root@localhost ~]# cat < test.txt
[root@localhost ~]# cat < test.txt > a.txt
等价于---> cp test.txt a.txt