linux命令greap linux命令grep 查询文件( 四 )


x\{m,n\}#重复字符x , 至少m次,不多于n次,如:'o\{5,10\}'匹配5--10个o的行 。
\w#匹配文字和数字字符,也就是[A-Za-z0-9],如:'G\w*p'匹配以G后跟零个或多个文字或数字字符,然后是p 。
\W#\w的反置形式,匹配一个或多个非单词字符,如点号句号等 。
\b#单词锁定符,如: '\bgrep\b'只匹配grep 。
POSIX字符:
为了在不同国家的字符编码中保持一至,POSIX(The Portable Operating System Interface)增加了特殊的字符类 , 如[:alnum:]是[A-Za-z0-9]的另一个写法 。要把它们放到[]号内才能成为正则表达式,如[A- Za-z0-9]或[[:alnum:]] 。在linux下的grep除fgrep外,都支持POSIX的字符类 。
[:alnum:]#文字数字字符
[:alpha:]#文字字符
[:digit:]#数字字符
[:graph:]#非空字符(非空格、控制字符)
[:lower:]#小写字符
[:cntrl:]#控制字符
[:print:]#非空字符(包括空格)
[:punct:]#标点符号
[:space:]#所有空白字符(新行,空格,制表符)
[:upper:]#大写字符
[:xdigit:]#十六进制数字(0-9,a-f,A-F)
5.使用实例:
实例1:查找指定进程
命令:
ps -ef|grep svn
输出:
[root@localhost ~]# ps -ef|grep svn
root 494310Dec05 ?00:00:00 svnserve -d -r /opt/svndata/grape/
root 16867 168380 19:53 pts/000:00:00 grep svn
[root@localhost ~]#
说明:
第一条记录是查找出的进程;第二条结果是grep进程本身 , 并非真正要找的进程 。
实例2:查找指定进程个数
命令:
ps -ef|grep svn -c
ps -ef|grep -c svn
输出:
[root@localhost ~]# ps -ef|grep svn -c
2
[root@localhost ~]# ps -ef|grep -c svn
2
[root@localhost ~]#
说明:
实例3:从文件中读取关键词进行搜索
命令:
cat test.txt | grep -f test2.txt
输出:
[root@localhost test]# cat test.txt
hnlinux
peida.cnblogs.com
ubuntu
ubuntu linux
redhat
Redhat
linuxmint
[root@localhost test]# cat test2.txt
linux
Redhat
[root@localhost test]# cat test.txt | grep -f test2.txt
hnlinux
ubuntu linux
Redhat
linuxmint
[root@localhost test]#
说明:
输出test.txt文件中含有从test2.txt文件中读取出的关键词的内容行
实例3:从文件中读取关键词进行搜索 且显示行号
命令:
cat test.txt | grep -nf test2.txt
输出:
[root@localhost test]# cat test.txt
hnlinux
peida.cnblogs.com
ubuntu
ubuntu linux
redhat
Redhat
linuxmint
[root@localhost test]# cat test2.txt
linux
Redhat
[root@localhost test]# cat test.txt | grep -nf test2.txt
1:hnlinux
4:ubuntu linux
6:Redhat
7:linuxmint
[root@localhost test]#
说明:
输出test.txt文件中含有从test2.txt文件中读取出的关键词的内容行,并显示每一行的行号
实例5:从文件中查找关键词
命令:
grep 'linux' test.txt
输出:
[root@localhost test]# grep 'linux' test.txt
hnlinux
ubuntu linux
linuxmint
[root@localhost test]# grep -n 'linux' test.txt
1:hnlinux
4:ubuntu linux
7:linuxmint
[root@localhost test]#
说明:
实例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

推荐阅读