grep

grep系列命令概述

grep来自于英文词组“global search regular expression and print out the line”的缩写,意思是用于全面搜索的正则表达式,并将结果输出。人们通常会将grep命令与正则表达式搭配使用,参数作为搜索过程中的补充或对输出结果的筛选,命令模式十分灵活。

与之容易混淆的是egrep命令和fgrep命令。如果把grep命令当作是标准搜索命令,那么egrep则是扩展搜索命令,等价于“grep -E”命令,支持扩展的正则表达式。而fgrep则是快速搜索命令,等价于“grep -F”命令,不支持正则表达式,直接按照字符串内容进行匹配。

grep基本使用

[root@fedora ~]# grep --help
Usage: grep [OPTION]... PATTERNS [FILE]...
Search for PATTERNS in each FILE.
......
[root@fedora ~]# grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@fedora ~]# ps -ef | grep "/sbin/sshd"
root       11479    2279  0 18:54 pts/0    00:00:00 grep --color=auto /sbin/sshd

 grep常用选项

[root@fedora ~]# grep -n '^root:' /etc/passwd
1:root:x:0:0:root:/root:/bin/bash

grep的匹配选择器

-G:基本的正则表达式(默认选项,可省略)

-E:拓展的正则表达式()

-F:不支持正则表达式

-P:perl风格的正则表达式

grep使用的正则表达式元字符

grep退出状态码

[root@fedora ~]# grep 'root' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@fedora ~]# $?
bash: 0: command not found...
# 退出码为0,找到

[root@fedora ~]# grep 'alice' /etc/passwd
[root@fedora ~]# $?
bash: 1: command not found...
# 退出码为1,未找到

[root@fedora ~]# grep 'root' /etc/asd
grep: /etc/asd: No such file or directory
[root@fedora ~]# $?
bash: 2: command not found...
# 退出码为2,文件访问失败

 egrep使用的正则表达式元字符

posted @ 2022-06-11 19:37  CharlieBrown  阅读(148)  评论(0)    收藏  举报
标题