linux grep

时间:2024-05-03 08:38:08

grep (缩写来自Globally search a Regular Expression and Print)

是一种强大的文本搜 索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。Unix的grep家族包括

grep、egrep和fgrep

案例1:精确的匹配

[root@localhost ~]# cat 1.txt | grep

all all tooall to

alltoall all allto100

uuualltoall

[root@localhost ~]# cat 1.txt | grep -w "all"

all tooall to

alltoall all

案例2:加入自动颜色

[root@localhost ~]# cat 1.txt | grep -w "all" --color=auto

all tooall

to alltoall all

案例3 :取反参数 -v 选项
[root@localhost ~]# ps -ef | grep ssh

root       2055      1  0 09:03 ?        00:00:00 /usr/sbin/sshd

root      24498   2055  0 11:21 ?        00:00:01 sshd: root@pts/0

root      24657  24502  0 12:11 pts/0    00:00:00 grep ssh

[root@localhost ~]# ps -ef | grep ssh | grep -v grep

root       2055      1  0 09:03 ?        00:00:00 /usr/sbin/sshd

root      24498   2055  0 11:21 ?        00:00:01 sshd: root@pts/0

[root@localhost ~]

案例4 :统计出现的次数
[root@localhost ~]# grep -c "all" 1.txt

4

[root@localhost ~]#

案例5:显示匹配的行数

[root@localhost ~]# grep -n "all"

1.txt 1:all tooall

2:to alltoall all

3:allto100

4:uuualltoall

案例6:显示匹配的文件

[root@localhost ~]# grep "all" 1.txt 2.txt 4.txt

1.txt:all tooall

1.txt:to alltoall all

1.txt:allto100

1.txt:uuualltoall

2.txt:alltohell

2.txt

4.txt:allheot4.txt

[root@localhost ~]# grep -l "all" 1.txt 2.txt 4.txt

1.txt

2.txt

4.txt

案例7:忽略字符大小写
[root@localhost ~]# cat 1.txt | grep -i "ALL"

all tooall

ALAALLL

to alltoall all

allto100

uuualltoall