龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 操作系统 > LINUX系统 >

linux命令大全之grep命令详解(文本搜索工具)(3)

时间:2014-05-19 15:24来源:网络整理 作者:网络 点击:
分享到:
实例6:从多个文件中查找关键词 命令:grep 'linux' test.txt test2.txt 输出: 代码如下: [root@localhost test]# grep -n 'linux' test.txt test2.txt test.txt:1:hnlinux test.txt:4:ubu

实例6:从多个文件中查找关键词
命令:grep 'linux' test.txt test2.txt
输出:

代码如下:

[root@localhost test]# grep -n 'linux' test.txt test2.txt
test.txt:1:hnlinux
test.txt:4:ubuntu linux
test.txt:7:linuxmint
test2.txt:1:linux
[root@localhost test]# grep 'linux' test.txt test2.txt
test.txt:hnlinux
test.txt:ubuntu linux
test.txt:linuxmint
test2.txt:linux
[root@localhost test]#

说明:多文件时,输出查询到的信息内容行时,会把文件的命名在行最前面输出并且加上":"作为标示符

实例7:grep不显示本身进程
命令:

代码如下:

ps aux|grep \[s]sh
ps aux | grep ssh | grep -v "grep"

输出:

代码如下:

[root@localhost test]# ps aux|grep ssh
root 2720 0.0 0.0 62656 1212 ? Ss Nov02 0:00 /usr/sbin/sshd
root 16834 0.0 0.0 88088 3288 ? Ss 19:53 0:00 sshd: <a href="mailto:root@pts/0">root@pts/0</a>
root 16901 0.0 0.0 61180 764 pts/0 S+ 20:31 0:00 grep ssh
[root@localhost test]# ps aux|grep \[s]sh]
[root@localhost test]# ps aux|grep \[s]sh
root 2720 0.0 0.0 62656 1212 ? Ss Nov02 0:00 /usr/sbin/sshd
root 16834 0.0 0.0 88088 3288 ? Ss 19:53 0:00 sshd: <a href="mailto:root@pts/0">root@pts/0</a>
[root@localhost test]# ps aux | grep ssh | grep -v "grep"
root 2720 0.0 0.0 62656 1212 ? Ss Nov02 0:00 /usr/sbin/sshd
root 16834 0.0 0.0 88088 3288 ? Ss 19:53 0:00 sshd: <a href="mailto:root@pts/0">root@pts/0</a>

实例8:找出已u开头的行内容
命令:cat test.txt |grep ^u
输出:

代码如下:

[root@localhost test]# cat test.txt |grep ^u
ubuntu
ubuntu linux
[root@localhost test]#

实例9:输出非u开头的行内容
命令:cat test.txt |grep ^[^u]
输出:

代码如下:

[root@localhost test]# cat test.txt |grep ^[^u]
hnlinux
peida.cnblogs.com
redhat
Redhat
linuxmint
[root@localhost test]#

实例10:输出以hat结尾的行内容
命令:cat test.txt |grep hat$
输出:

代码如下:

[root@localhost test]# cat test.txt |grep hat$
redhat
Redhat
[root@localhost test]#

实例11:
命令: ifconfig eth0|grep "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}"
输出:

代码如下:

[root@localhost test]# ifconfig eth0|grep "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}"
inet addr:192.168.120.204 Bcast:192.168.120.255 Mask:255.255.255.0
[root@localhost test]# ifconfig eth0|grep -E "([0-9]{1,3}\.){3}[0-9]"
inet addr:192.168.120.204 Bcast:192.168.120.255 Mask:255.255.255.0
[root@localhost test]#

实例12:显示包含ed或者at字符的内容行
命令:cat test.txt |grep -E "ed|at"
输出:

代码如下:

[root@localhost test]# cat test.txt |grep -E "peida|com"
peida.cnblogs.com
[root@localhost test]# cat test.txt |grep -E "ed|at"
redhat
Redhat
[root@localhost test]#

实例13:显示当前目录下面以.txt 结尾的文件中的所有包含每个字符串至少有7个连续小写字符的字符串的行
命令:grep '[a-z]\{7\}' *.txt
输出:

代码如下:

[root@localhost test]# grep '[a-z]\{7\}' *.txt
test.txt:hnlinux
test.txt:peida.cnblogs.com
test.txt:linuxmint
[root@localhost test]#

精彩图集

赞助商链接