主要用于字符串的模式分割、匹配、查找及替换操做。正则表达式
通配符 | 做用 |
---|---|
* | 匹配任意内容 |
? | 匹配任意一个内容 |
[] | 匹配中括号的一个字符 |
通配符 *code
[root@localhost ~]# ls *.txt 1.txt 2.txt a.txt
通配符 ?字符串
[root@localhost ~]# ls 1?3 123
通配符 [ ]table
[root@localhost ~]# ls [0-9].txt 1.txt 2.txt
字符 | 做用 |
---|---|
* | 前一个字符匹配0次或任意屡次 |
. | 匹配除了换行符外任意一个字符 |
^ | 匹配行首 |
& | 匹配行尾 |
[] | 匹配中括号中指定的任意一个字符,只匹配一个字符 |
\ | 转义符 |
\ {n\ } | 表示其前面的字符刚好出现n次 |
\ {n,m\ } | 匹配其前面的字符至少出现n次,最多出现m次 |
匹配全部内容,包括空白行。test
[root@localhost ~]# grep "a*" test.txt a aa aaa aaaa aaaaa ab aabb b bb bbb bbbb bbbbb
[root@localhost ~]# grep "aa*" test.txt a aa aaa aaaa aaaaa ab aabb
[root@localhost ~]# grep "aaa*" test.txt aa aaa aaaa aaaaa aabb
匹配最少包含四个连续a的字符串。基础
[root@localhost ~]# grep "aaaaa*" test.txt aaaa aaaaa
[root@localhost ~]# cat test.txt a aa aaa aaaa aaaaa ab aabb root raat rabcdet b bb bbb bbbb bbbbb [root@localhost ~]# grep "r..t" test.txt root raat
[root@localhost ~]# grep "r.*t" test.txt root raat rabcdet
[root@localhost ~]# grep ".*" test.txt a aa aaa aaaa aaaaa ab aabb root raat rabcdet b bb bbb bbbb bbbbb
[root@localhost ~]# grep "^r" test.txt root raat rabcdet
[root@localhost ~]# grep "t$" test.txt root raat rabcdet
[root@localhost ~]# grep -n "^$" test.txt 11: 13:
使用这个命令会打印出空格行grep
[root@localhost ~]# cat test.txt a aa aaa aaaa aaaaa ab aabb root raat rabcdet b aaa123 123 456 789 1234567890 aaa123bbb 123bbb bb bbb bbbb bbbbb [root@localhost ~]# grep "r[ao]at" test.txt raat
[root@localhost ~]# grep -n "[0-9]" test.txt 13:aaa123 14:123 15:456 16:789 17:1234567890 18:aaa123bbb 19:123bbb
[root@localhost ~]# grep -n "^[a-z]" test.txt 1:a 2:aa 3:aaa 4:aaaa 5:aaaaa 6:ab 7:aabb 8:root 9:raat 10:rabcdet 12:b 13:aaa123 18:aaa123bbb 21:bb 22:bbb 23:bbbb 24:bbbbb
[root@localhost ~]# grep -n "^[^a-z]" test.txt 14:123 15:456 16:789 17:1234567890 19:123bbb
能够将特殊符号的做用取消,再也不具备特殊做用tab
[root@localhost ~]# grep ".$" test.txt a aa aaa aaaa aaaaa ab aabb root. raat. rabcdet b aaa123 123 456 789 1234567890 aaa123bbb 123bbb bb bbb bbbb bbbbb
此种操做是错误的,由于“.” 这里具备特殊的含义, 表示以任意字符结尾的列出。 在这里须要加上转义符。列出以“.” 结尾的行文件
[root@localhost ~]# grep -n "\.$" test.txt 8:root. 9:raat.
[root@localhost ~]# cat test.txt 2018-06-05 20180605 180605 [root@localhost ~]# grep "[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}" test.txt 2018-06-05
[root@localhost ~]# grep "[0-9]\{1\}[0-9]\{1\}[0-9]\{1\}[0-9]\{1\}[0-9]\{1\}[0-9]\{1\}[0-9]\{1\}[0-9]\{1\}[0-9]\{1\}[0-9]\{1\}[0-9]\{1\}" test.txt 13911111111
[root@localhost ~]# grep "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}" test.txt 192.168.1.1