主要用於字符串的模式分割、匹配、查找及替換操做。正則表達式
通配符 | 做用 |
---|---|
* | 匹配任意內容 |
? | 匹配任意一個內容 |
[] | 匹配中括號的一個字符 |
通配符 *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