互联网科技程序员Linux学习|Gentoo/Arch/FreeBSD

Linux运维之道(9)——Linux三剑客之grep命令及其正

2016-03-28  本文已影响1330人  逃跑中计划

@(Linux)[Linux三剑客之grep及其正则表达式]


HowTo: Use grep Command In Linux / UNIX ?

Can you give me a simple examples of the grep command?

How do I use grep command on Linux, Apple OS X, and Unix-like operating systems?

The grep command is used to search text or searches the given file for lines containing a match to the given strings or words. By default, grep displays the matching lines. Use grep to search for lines of text that match one or many regular expressions, and outputs only the matching lines. grep is considered as one of the most useful commands on Linux and Unix-like operating systems.


1. grep命令

grep: grep, egrep, fgrep - print lines matching a pattern
文本搜索工具,根据用户指定的“模式”对目标文本逐行进行匹配检查,打印匹配到的行。

模式:由正则表达式字符及文本字符所编写的过滤条件;

REGEXP:由一类特殊字符及文本字符所编写的模式,其中有些字符不表示字符字面意义,而表示控制或通配的功能;

正则表达式:

格式:
grep [OPTIONS] PATTERN [FILE...]
grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]

参数选项:

2. 基本正则表达式

2.1 字符匹配

2.2 贪婪模式

2.3 位置锚定

2.4 分组

\(ab\+\(xy\)*\)\1代表ab\+\(xy\)*\2代表xy

Note:
1、分组括号中的模式匹配到的内容会被正则表达式引擎记录于内部的变量中
2、这些变量的命名方式为: \1, \2, \3, ...
3、\1: 从左侧起,第一个左括号以及与之匹配右括号之间的模式所匹配到的字符
4、后向引用:引用前面的分组括号中的模式所匹配字符(而非模式本身)

2.5 实战演示

1、如果用户root存在,显示其默认的shell程序
# id root &> /dev/null && grep "^root\>" /etc/passwd | cut -d: -f7

2、找出/etc/passwd中的两位或三位数
# grep "\<[0-9]\{2,3\}\>" /etc/passwd

3、显示/etc/rc.d/rc.sysinit文件中,至少以一个空白字符开头的且后面存非空白字符的行
# grep "^[[:space:]]\+[^[:space:]]" /etc/grub2.cfg

4、找出"netstat -tan"命令的结果中以'LISTEN'后跟0、1或多个空白字符结尾的行;
# netstat -tan | grep "LISTEN[[:space:]]*$"

3. 扩展的正则表达式

3.1 字符匹配

3.2 次数匹配

3.3 锚定

3.4 分组

后向引用
\1, \2, ...
或者使用 a | b
C | cat

3.5 实战演示

1、显示当前系统root、centos或user1用户的默认shell和UID;
# grep -E '^(root|centos|user1)\>' /etc/passwd | cut -d: -f1,3,7

2、找出/etc/rc.d/init.d/functions文件(centos6)中某单词后面跟一个小括号的行;
# grep -E -o "^[_[:alpha:]]+\(\)" /etc/rc.d/init.d/functions

3、使用echo输出一绝对路径,使用egrep取出其基名;
# echo "/mnt/sdc" | grep -E -o "[^/]+/?$" | cut -d"/" -f1

4. egrep and fgrep

4.1 egrep命令

egrep = grep -E

4.2 fgrep命令

fgrep:不支持正则表达式搜索,能够很快的进行搜索


5. 思维导图

Linux三剑客之grep及其正则表达式
上一篇 下一篇

猜你喜欢

热点阅读