一、简介:过滤,查找文档中的内容
二、分类
- grep
- egrep------扩展支持正则
- \w所有字母与数字,称为字符[a-zA-Z0-9] 'l[a-zA-Z0-9]*ve' === 'l\w*ve'
- \W所有字母与数字之外的字符,称为非字符 'love[^a-zA-Z0-9]+' === 'love\W+'
- \b词边界 '\<love\>' === '\blove\b'
- fgrep------不支持正则
cs
[root@localhost ~]# fgrep . 1.txt
l.ve
三、返回值
- 0 是找到
- 1 是没有
- 2 找到地不对
cs
[root@localhost ~]# grep 'root' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@localhost ~]# echo $?
0
[root@localhost ~]# grep 'root1' /etc/passwd
[root@localhost ~]# echo $?
1
[root@localhost ~]# grep 'root' /etc/passwd1
grep: /etc/passwd1: 没有那个文件或目录
[root@localhost ~]# echo $?
2
四、参数
cs
#grep -q 静默
[root@localhost ~]# grep -q love 1.txt
[root@localhost ~]# echo $?
0
#grep -v 取反
[root@localhost ~]# grep -v love 1.txt
#qian
#yoa
#huang
kai
kong
cai
#grep - R 可以查目录下面的
[root@localhost ~]# grep -R kai /home
/home/1.txt:kai
#grep -o 只找到这个关键字
[root@localhost ~]# grep -o love 1.txt
love
love
#grep - B2 前两行
[root@localhost ~]# grep -B2 love 1.txt
abcdefj
adc
love
#grep - A2 后两行
[root@localhost ~]# grep -A2 love 1.txt
love
Love
1ove
#grep -C2 上下两行
[root@localhost ~]# grep -C2 love 1.txt
abcdefj
adc
love
Love
#egrep -l 只要文件名
[root@localhost ~]# egrep -l -R kai /home
/home/1.txt
#egrep -n 带行号
[root@localhost ~]# grep -n love 1.txt
14:love
21:loveable
五、示例
cs
//grep -E或 egrep 使用
# egrep 'NW' datafile.txt
# egrep 'NW' d*.txt
# egrep '^n' datafile.txt
# egrep '4$' datafile.txt
# egrep TB Savage datafile.txt
# egrep 'TB Savage' datafile.txt
# egrep '5\..' datafile.txt
# egrep '1.5' datafile.txt
# egrep'^[we]' datafile.txt
# egrep '[^0-9]' datafile
# egrep '[A-Z][A-Z] [A-Z]' datafile
# egrep'ss*'datafile
# egrep '[a-Z](9)' datafile L
# egrep I<north' datafile
# egrep l<northi>' datafile
# egrep l<[a-rj.*nl>' datafile
# egrep '^nlw*\W' datafile
# egrep lbnorthib' datafile
# egrep 'NW | EA' datafile
# egrep '3+' datafile
# egrep '2\.?[0-9]' datafile
# egrep(no)+' datafile
# egrep 'S(hlu)' datafile
# egrep 'Sh lu' datafile