【每天一个linux命令】grep

参考:

【linux grep命令详解】http://www.cnblogs.com/ggjucheng/archive/2013/01/13/2856896.html

【linux命令中使用正则表达式】http://www.cnblogs.com/Quincy/archive/2012/03/26/2418485.html  

简介

grep:一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来

【grep常用用法】

grep [-acinv] [--color=auto] '搜寻字符串' filename
选项与参数:
-a :将 binary 文件以 text 文件的方式搜寻数据
-c :计算找到 '搜寻字符串' 的次数
-i :忽略大小写的不同
-n :输出行号
-v :反向选择,亦即显示出没有 '搜寻字符串' 内容的那一行!
--color=auto :'搜寻字符串' 显示颜色

【实例】

1、搜索文件中的字段/行

# 打印有 "hello"的行,不区分大小写,标行号、颜色
[service@ndl-bass-ys-vm-129-186 wy]$ grep -in --color=auto hello yy.log 
2:hello,wolrd:nihao
3:HELLO

# 同时有 xx和xxx 的行
[service@ndl-bass-ys-vm-129-186 wy]$ grep -E 'WARNING|FATAL' a.log 
WARNING fsjfs
WARNING hello:FATAL/IGNOR
#打印没有"hello"的行
[service@ndl-bass-ys-vm-129-186 wy]$ grep -v hello yy.log              
ERROR suscess
HELLO

# 打印没有 hello 和 error 的行
[service@ndl-bass-ys-vm-129-186 wy]$ grep -v hello yy.log |grep -iv error
HELLO

# a中有,b中没有的
grep -xvf a b

# ab中共同有的
grep -xf a b
#  关键字所在行的 前1行(B1),后2行(A2) 打印出
[service@ndl-bass-ys-vm-129-186 wy]$ grep -B1 -A2 --color=auto hello yy.log  
ERROR suscess
hello,wolrd:nihao
HELLO
suscess

2、搜索文件

# 搜索当前目录带 error 的文件
[service@ndl-bass-ys-vm-129-186 wy]$ grep -i error *             
Binary file clean.jar matches
new:ERROR suscess
yy.log:ERROR suscess
yy.log:ERRORend
# 当前目录及其子目录
[service@ndl-bass-ys-vm-129-186 wy]$ grep -r ERROR * 
new:ERROR suscess
yy.log:ERROR suscess
yy.log:ERRORend
# 当前目录及其子目录,只显示文件名,不显示具体行
[service@ndl-bass-ys-vm-129-186 wy]$ grep -r -l ERROR *
new
yy.log

 【grep正则表达式

1、匹配数字

# 模糊匹配数字
[service@ndl-bass-ys-vm-129-186 wy]$ grep '2017-06-1[0-9]' yy.log   
[INFO2] [2017-06-12 17:34:02][streaming]数据文件清洗-->开始
[INFO3] [2017-06-13 17:34:02][streaming]数据文件清洗-->开始

# 匹配所有有数字的行
[service@ndl-bass-ys-vm-129-186 wy]$ grep '[0-9][0-9]*' yy.log 
[1info][2017]
[INFO2] [2017-06-12 17:34:02][streaming]数据文件清洗-->开始
[INFO3] [2017-06-13 17:34:02][streaming]数据文件清洗-->开始

2、匹配以 xx 开头的

# 匹配以小写字母开头
# a-z,小写字母;a-zA-Z 字母
[service@ndl-bass-ys-vm-129-186 wy]$ grep '^[a-z]' yy.log              
hello,wolrd:nihao
hollo
suscess

# ^[xx] 匹配以xx开头
[service@ndl-bass-ys-vm-129-186 wy]$ grep '^[ERROR]' yy.log   
ERROR suscess
ERRORend

# [^xx]反向匹配;^在[]外是以xx开头,^在[]内反向匹配
[service@ndl-bass-ys-vm-129-186 wy]$ grep ^[^a-zA-Z] yy.log
你好
[1info][2017]

3、匹配以 xx 结尾

# 匹配以 ] 结尾的
[service@ndl-bass-ys-vm-129-186 wy]$ grep ']$' yy.log
[1info][2017]
[infoend] [dsds]

# 以 . 结尾(.是特殊字符,要 转义字符 \ 匹配)
[service@ndl-bass-ys-vm-129-186 wy]$ grep '\.$' yy.log 
hollo.

 

posted @ 2017-11-07 16:34  白小白001  阅读(260)  评论(0编辑  收藏  举报