linux grep工作常用

来源:互联网 发布:江苏移动网络怎么样 编辑:程序博客网 时间:2024/05/29 10:47

本文主要是工作中grep的常见使用:
1. grep日志统计(单个多个文件)计数
2. grep and or not
3. grep 多个文件匹配查找
4. grep -A -B 关键匹配前后几行的重要信息

grep -c ‘text’ filename(log指定text行数统计)


工作中我们往往要统计日志中某些字符串(一行行)的统计信息,
一般 grep ‘text’ filename | wc -l
其实: grep -c ‘text’ filename 更简单直接统计行数

$ grep -c "go" demo_text6When you want do find out how many lines that does not match the pattern$ grep -v -c this demo_file4    

grep or 查询


  1. grep ‘pattern1|pattern2’ filename

  2. grep -E ‘pattern1|pattern2’ filename

  3. egrep ‘pattern1|pattern2’ filename

  4. grep -e pattern1 -e pattern2 filename

例如统计文件数量的时候(往往第一行要减掉)

root@ubuntu:/data6/light/images/others# grep -c -e "JPEG" -e"jpg" <(ll)16581root@ubuntu:/data6/light/images/others# grep -c "" <(ll)16582

grep and 查询


  1. grep -E ‘pattern1.*pattern2’ filename

  2. grep -E ‘pattern1.*pattern2|pattern2.*pattern1’ filename

grep not 查询

grep -v

grep practice(-A -B..)


比如在查看caffe训练的时候,看accuracy同时看前后两行的loss信息以及learning rate
这里写图片描述

grep -inr “Text” folder/to/be/searched/搜索当前目录下所有含有”Text”的文件

这里写图片描述

The r stands for recursive and so will search in the path specified and also its sub-directories. (循环递归当前目录以及子目录)

i stands for ignore case (optional in your case).(忽略大小写)
-n is line number

If your grep doesn’t support recursive search, you can combine find with xargs:

find / -type f | xargs grep ‘text-to-find-here’
当前目录下查找txt文件
find . -name “*.txt” | xargs grep -i “text_pattern”

Display only the file names which matches the given pattern using grep -l(查找含有指定字符串的文件)

$ grep -l this demo_*demo_filedemo_file1

Searching in all files recursively using grep -r(查找多有文件,这样方便统计日志)
$ grep -r “error_msg” *

linux命令的很多技巧基本google到的,很多参考下面这个bolg
http://www.thegeekstuff.com/category/sed/

关键词英文对了,很多问题瞬间解决。