您的位置:首页 > 运维架构 > Linux

linux命令学习03-grep

2016-04-05 17:47 651 查看
实例1、查找某个进程

#ps -ef | grep ssh

root 1771 1 0 12:07 ? 00:00:00 /usr/sbin/sshd
root 2362 1771 0 16:34 ? 00:00:00 sshd: root@pts/0
root 2409 2364 0 16:36 pts/0 00:00:00 grep ssh

实例2、查找多个进程

#ps -ef|grep -E "ssh|crond"

root 1771 1 0 12:07 ? 00:00:00 /usr/sbin/sshd
root 1946 1 0 12:08 ? 00:00:00 crond
root 2362 1771 0 16:34 ? 00:00:00 sshd: root@pts/0
root 2424 2364 0 16:40 pts/0 00:00:00 grep -E crond|ssh

grep -E=egrep,表示采用extended regular expression(扩展正则表达式)语法来解读;

grep -e,表示后跟正则表达式;

实例3、把一个文件的内容当关键字进行检索其他文件

# cat >test.txt<<eof
> aaaa
> bbbb
> ccccc
> ddddd
> eeeee
> eof
# cat test.txt
aaaa
bbbb
ccccc
ddddd
eeeee
# cat >test1.txt<<eof
> ddd
> bbb
> eof
# cat test1.txt
ddd
bbb
# cat test.txt|grep -nf test1.txt
2:bbbb
4:ddddd

-n,表示显示行号,-f表示以文件为关键字

实例4、查找不包含关键字的行并显示行号

# cat test.txt|grep -vnE "cc|aa"
2:bbbb
4:ddddd
5:eeeee
# cat test.txt|egrep -vn "cc|aa"
2:bbbb
4:ddddd
5:eeeee

实例4、查找以e开头的行和不以e开头的行

# cat test.txt|grep ^e
eeeee
# cat test.txt|grep -n ^e
5:eeeee
# cat test.txt|grep -n ^[^e]
1:aaaa
2:bbbb
3:ccccc
4:ddddd

^表示以某关键字开头,[^]表示匹配一个不在指定范围内的字符,^[^e]表示非e开头的行

实例5、查找以dd结尾的行和不以c-m结尾的行

# cat test.txt|grep -n dd$
4:ddddd
7:bcdddd
8:xxdddd
# cat test.txt|grep -n [^c-m]$
1:aaaa
2:bbbb
6:abcdxx
11:lllnnn

实例6、查找文件中的ip地址

# cat test.txt|grep "[0-9]\{1,3\}.[0-9]\{1,3\}.[0-9]\{1,3\}.[0-9]\{1,3\}"
192.168.1.2
192.160.23.156
10.0.31.254
1.25.235.12

注:grep默认需要对{进行转义,必须添加\;

# cat test.txt|egrep "([0-9]{1,3}.){3}.[0-9]"
192.168.1.2
192.160.23.156
10.0.31.254
1.25.235.12

注:egrep不需要且不能对{} ()进行转义,添加转义\则查不出内容;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: