1、正则表达式

在日常处理日志的过程中,使用正则表达式的工具包括grep,sed,awk等,本次仅仅对grep和sed进行一些简单的介绍。
2、grep
grep [options] pattern [file-list]
grep可在一个或多个文件中逐行搜说pattern,pattern可以是简单的一个字符串,也可以是正则表达式。
参数选项:
-c(count) 显示每个文件中包含匹配的行的数目
-f (file) 读取文件file,从输入中查找匹配每个模式的行。
-I (ignore-case) 使得模式中的小写字母可以匹配其大写。使用该选项可以搜索到句子开始的单词可大写,也可小写
-l (files-with-matches) 仅显示包含匹配的文件名,每个文件名仅显示一次
-L (files-without-match) 显示不包含匹配的文件名
-n (line-number) 在显示的每行前显示行号
-v (invert-match) 显示不包含匹配的行
-w (word-regexp) pattern 必须与整个字匹配
-x (line-regexp) pattern 匹配整行
-h 当搜索多个文件时,在每行的开始不显示文件名
-H (with-filename) 为每个匹配显示文件名
-E (extended-regexp) 扩展正则表达式,grep –E 等价于egrep
-A (after-context=NUM) 显示匹配行以及前面的几行
-B (before-context=NUM) 显示匹配行以及后面的几行
-C (context=NUM) 显示匹配行以及前后的几行
以上只列出grep的一些常用的用法。一下分别针对正则表达式以及grep的示例进行实际操作。

1) 查找字符串 good

-n 显示行号
-H 显示文件名
在文件reg 文件中所搜含有good的行
2) 反向选择查找,使用-v 便可以查找不含goo的行

3) 搜索统计含有goo的行数

4) 搜索统计含有goo的行数


查找file文件中student和reg 匹配的行 5) 使用-i忽略大小写

6) 查找匹配的整个单词

使用-w 选项和正则表达式的 <> 匹配整个单词
// 以上只是grep的一些基本选项使用的一些示例,一下是对于正则表达式的操作
7) 查找含$(美元符号)的行

当遇到有特殊含义的行,需要用反斜线进行转义
8)句点.符号表示单个字符

9)星号*符号表示匹配它前0个或多个字符




12)匹配中括号中的任意一个字符


13)区间匹配

14)[:upper:] 和 [A-Z]

15)[:digit:] 和 [0-9]

16)[:lower:] 和 [a-z]

网友评论