查找包含root的行
grep root /etc/passwd
v:反相选择
grep -v root /etc/passwd
-i :忽略大小写
grep lihao test.txt
w:用于字符串精确匹配
grep -w dhcp test.txt
e:查找多个
grep lihao dhcp test.txt
grep -e lihao -e dhcp test.txt
不区分大小写,同时查找多个想要的内容
综合应用
grep -i -w -e lihao -e dhcp test.txt
c:显示查找后符合的行数
grep -c dhcp test.txt
也可以这样统计
grep dhcp test.txt | wc -l
n:显示行号
grep -n dhcp test.txt
grep -wn dhcp test.txt
-o:只显示匹配的字符串
grep -o root /etc/passwd
-q:不输出内容
grep -q root /etc/passwd
grep -q rooooot /etc/passwd
-A:显示匹配内容及以下的几行
grep -A root /etc/passwd 没定义到底显示几行
grep -A 2 root /etc/passwd
-B:显示匹配内容及以上的几行
grep -B 2 root /etc/passwd
-C:显示匹配内容的上下几行
grep -C 2 tss /etc/passwd
使用管道
cat test.txt | grep -i lihao
使用egrep查找多个内容
egrep ‘root|zs|lihao’ /etc/passwd
.:匹配任意一个字符
grep ‘s…d’ /etc/passwd
grep ‘…od’ /etc/passwd
[]:匹配指定范围内的任意单个字符
[^]:匹配指定范围外的任意单个字符
[:lower:]小写字母 [:upper:]大写字母 [:alpha:]大小写字母
grep ‘[[:alpha:]][[:alpha:]][[:alpha:]]t’ /etc/passwd
grep ‘…t’ /etc/passwd(使用3个点,会匹配/,它不是字符)
^:行首匹配
grep ^d /etc/passwd
:
行
尾
匹
配
g
r
e
p
0
:行尾匹配 grep 0
:行尾匹配grep0 /etc/fstab
^KaTeX parse error: Expected group after '^' at position 10: :空行 grep ^̲ /etc/login.defs
-E:扩展的正则表达式 | :或者
grep -E ‘^(root|zs|lihao)’ /etc/passwd