过滤文件内容 — grep
grep [option] “pattern” 文件名称
pattern模式:
由普通字符和正则表达式的元字符组成的条件
[root@tan /]# grep “root” /etc/passwd
正则表达式的元字符
1) 匹配单个字符的元字符
. 任意单个字符
[root@tan /]# grep “r…t” /etc/passwd
[abc]框里有的 或者
[root@tan /]# grep “r[aA]t” /tmp/1.txt
- 连续的字符范围
什么到什么当中的任意一个字符
[a-z] [A-Z] [a-zA-Z] [0-9] [a-zA-Z0-9]
[root@tan /]# grep “r[a-z]t” /tmp/1.txt
[root@tan /]# grep “r[0-9]t” /tmp/1.txt
[root@tan /]# grep “r[a-zA-Z0-9]t” /tmp/1.txt
^ 取反
[^a-z] 不是小写字母意思
[root@tan /]# grep “r[^0-9]t” /tmp/1.txt
特殊的字符集:
[[:punct:]] 任意单个标点
[[:space:]] 任意单个空白字符
[root@tan /]# grep “r[[:punct:]]t” /tmp/1.txt
[root@tan /]# grep “r[[:space:]]t” /tmp/1.txt
2)匹配字符出现的位置
^string 以什么什么东西开头
以root开头的行
[root@tan /]# grep “^root” /etc/passwd
root❌0:0:root:/root:/bin/bash
以rbh三个字母开头的
[root@tan /]# grep “1” /etc/passwd
root❌0:0:root:/root:/bin/bash
bin❌1:1:bin:/bin:/sbin/nologin
halt❌7:0:halt:/sbin:/sbin/halt
以不是rbh三个字母开头的
[root@tan /]# grep “[rbh]” /etc/passwd
$
string$ 以string结尾 以什么结尾
以bash结尾的
[root@tan /]# grep “bash$” /etc/passwd
root❌0:0:root:/root:/bin/bash
以nologin结尾的行数
[root@tan /]# grep “nologin$” /etc/passwd | wc -l
15
^$ 空行的意思
统计空行的个数
[root@tan /]# grep “^$” /etc/fstab | wc -l
1
查找某个目录(etc)里的所有目录,过滤文件和软连接
[root@tan /]# ls -l /etc/ | grep “^d” (查看etc里的详细信息,管道符,过滤筛选以d(目录)开头的)
drwxr-xr-x. 2 root root 236 2月 26 01:02 alternatives
drwxr-x—. 3 root root 43 2月 26 01:02 audisp
drwxr-x—. 3 root root 83 2月 26 01:10 audit
drwxr-xr-x. 2 root root 22 2月 26 01:02 bash_completion.d
drwxr-xr-x. 2 root root 6 10月 31 2018 binfmt.d
drwxr-xr-x. 2 root root 6 8月 4 2017 chkconfig.d
小结:
. []
^ $ ^$
3) 匹配字符出现的次数
* 匹配前一个字符出现任意次数
[root@tan /]# grep “ab*” /tmp/2.txt
. * 任意长度的任意字符
[root@tan /]# grep “.*” /tmp/2.txt
\? 0次或者1次 可有可无
[root@tan /]# grep “ab?” /tmp/2.txt
+ 1次或者多次 最少出现1次
[root@tan /]# grep “ab+” /tmp/2.txt
{n} 表示精确出现几次
[root@tan /]# grep “ab{2}” /tmp/2.txt
{n,m} 表示最少几次,最多几次
[root@tan /]# grep “ab{2,5}” /tmp/2.txt
{n,} 表示最少几次,多了不限
[root@tan /]# grep “ab{2,}” /tmp/2.txt
(ab)+ 分组,反向引用
[root@tan /]# grep “(ab){2,}” /usr/share/dict/words
小结:以下统称正则表达式里的元字符
表示单个字符:
. []
表示位置:
^ $
次数:
*
+
?
{n}
{n,m}
{n,}
rbh ↩︎