Skip to content Skip to main navigation Skip to footer

Grep:grep如何同时查找多个字符串匹配

何通过grep 命令去查找多个字符串模式呢?例如我想通过grep命令来同时查找user1,user2,user3,如何来实现呢?
grep命令可以使用正则表达式来做字符串的匹配,为了查找多个字符,我们可以使用下面的命令:

[root@devops ~]# grep 'user1\|user2\|user3' /etc/passwd
user1:x:501:501::/home/user1:/bin/bash
user1add:x:503:503::/home/user1add:/bin/bash
user2:x:504:504::/home/user2:/bin/bash
user3:x:505:505::/home/user3:/bin/bash
[root@devops ~]#

如果想只匹配整个单词,可以使用-w 选项: 

[root@devops ~]# grep -w 'user1\|user2\|user3' /etc/passwd
user1:x:501:501::/home/user1:/bin/bash
user2:x:504:504::/home/user2:/bin/bash
user3:x:505:505::/home/user3:/bin/bash

grep命令的扩展版本egrep,带有更复杂的正则表达式元字符,对于上面的例子,如果使用egrep,那么可以省略转义字符,如下:

[root@devops ~]# egrep -w 'user1|user2|user3' /etc/passwd
user1:x:501:501::/home/user1:/bin/bash
user2:x:504:504::/home/user2:/bin/bash
user3:x:505:505::/home/user3:/bin/bash

如果想让查找到信息高亮显示,那么可以使用–color选项

[root@devops ~]# egrep -w --color 'user1|user2|user3' /etc/passwd
user1:x:501:501::/home/user1:/bin/bash
user2:x:504:504::/home/user2:/bin/bash
user3:x:505:505::/home/user3:/bin/bash
0 Comments

There are no comments yet

Leave a comment

Your email address will not be published.