grep 和 egrep

[TOC]

grep

前言

本文主要介绍了grepegrep的基础语法,读完本文可以基本掌握grepegrep的使用

grep

定义

grep (global search regular expression(RE) and print out the line, 全面搜索正则表达式并把行打印出来) 是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。

基础常用用法

[root@www ~]# grep [-acinv] [--color=auto] [-A n] [-B n] '搜寻字符串' 文件名

选项与参数:
-a :将 binary 文件以 text 文件的方式搜寻数据(基本没用过)
-c :计算找到 '搜寻字符串' 的次数(用得少)
-i :忽略大小写的不同,所以大小写视为相同 (用得少)
-n :顺便输出行号(用得少)
-v :反向选择,亦即显示出没有 '搜寻字符串' 内容的那一行!(用的很多)
-A:After的意思,显示匹配字符串后n行的数据
-B:before的意思,显示匹配字符串前n行的数据
-C是匹配行和它前后各n行。

将 /etc/passwd,出现root的行取出来

➜  ~ grep root /etc/passwd
root:*:0:0:System Administrator:/var/root:/bin/sh
daemon:*:1:1:System Services:/var/root:/usr/bin/false
_cvmsroot:*:212:212:CVMS Root:/var/empty:/usr/bin/false

将 / etc/passwd,有出现 root 的行取出来, 同时显示这些行在 / etc/passwd 的行号

➜  ~ grep -n root /etc/passwd
12:root:*:0:0:System Administrator:/var/root:/bin/sh
13:daemon:*:1:1:System Services:/var/root:/usr/bin/false
62:_cvmsroot:*:212:212:CVMS Root:/var/empty:/usr/bin/false

将 / etc/passwd,将没有出现 root 的行取出来

➜  ~ grep -v root /etc/passwd
##
# User Database

正则表达式

-w985

egrep

定义

egrep即扩展grep。等同于grep -E 。 可用于扩展正则表达式

扩展正则表达式

? : 匹配0个或1个在其之前的那个普通字符。

# 如,匹配gd,god   
grep –nE ‘go?d’ regular.txt

+ : 匹配1个或多个在其之前的那个普通字符,重复前面字符1到多次。

例如:匹配god,good,goood等等字符串。
grep –nE go+d’ regular.txt

(): 表示一个字符集合. 或用在expr中,匹配整个括号内的字符串,

例如:搜寻good或者glad
grep –nE ‘g(哦哦|la)’ regular.txt

|: 表示“或”. 或(or)的方式匹配多个字串。

# 例如:匹配god或者good。
grep –nE ‘god|good’ regular.txt 

你可能感兴趣的:(grep 和 egrep)