GREP命令学习笔记

GREP命令,全称:Global search REgular expression and Print out the line.

是一个非常强大的文本搜索命令,与SED(stream editor,文本编辑工具)和AWK(文本分析、报告生成器)并称文本处理三剑客。

一.GREP命令基本使用格式

grep [OPTIONS] PATTERN [FILE…]

 选项: 

   –color=auto: 对匹配到的文本着色显示;

  -v: 显示不能够被pattern匹配到的行,反转;

  -i: 忽略字符大小写;

  -o: 仅显示匹配到的字符串;

  -q: 静默模式,不输出任何信息;

  -A #:after, 后#行

  -B #: before, 前#行

  -C #:context, 前后各#行

  -E:使用ERE;

1. –color=auto参数是对匹配到的文本着色显示,Centos7中,grep的命令别名默认带了这个参数。

[root@192 ~]# alias grep
alias grep='grep --color=auto'

2.使用–v 参数显示不能够被匹配到的行

[root@192 ~]# grep -v /sbin/nologin /etc/passwd
root:x:0:0:root:/root:/bin/bash
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt

3.使用–i参数忽略大小写查找

[root@192 ~]# grep -i root /etc/fstab 
/dev/mapper/centos-root /   xfs    defaults   0 0

4. 使用–o参数仅显示匹配到的字符串

[root@192 ~]# grep -o root /etc/fstab
root

5. 使用-A,-B,-C显示之前、之后、(之前之后)的几行

-A,显示匹配行之后的几行

[root@192 ~]# grep -A2 mail /etc/passwd
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin

-B:显示匹配行之前的几行

[root@192 ~]# grep -B2 mail /etc/passwd
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin

-C:显示之前之后的几行

[root@192 ~]# grep -C2 mail /etc/passwd
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin

6.使用-n参数在输出时,显示行号

[root@192 ~]# grep -nA2  mail /etc/passwd
9:mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
10-operator:x:11:0:operator:/root:/sbin/nologin
11-games:x:12:100:games:/usr/games:/sbin/nologin

7.用-c参数统计显示匹配的行数

[root@192 ~]# grep -c root /etc/passwd
2

8.使用-r进行递归搜索,可以在当前目录及其子目录中进行搜索。

[root@192 ~]# grep -r /bashrc /etc/
/etc/bashrc:# /etc/bashrc
/etc/profile:# Functions and aliases go in /etc/bashrc
/etc/profile.d/256term.sh:# This must be set before reading global initialization such as /etc/bashrc.
/etc/skel/.bashrc:if [ -f /etc/bashrc ]; then
/etc/skel/.bashrc:      . /etc/bashrc

二.GREP的进阶用法

GREP命令可以根据用户指定的“模式”对目标文本逐行进行匹配检查,并且打印输出匹配到行(模式,是指由正则表达式字符及文本字符所编写的过滤条件)。

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

正则表达式分为基本正则表达式(BRE)和 扩展正则表达式(ERE)

2.1基本正则表达式用法及相关参数:

基本正则表达式元字符(BRE):

参数

字符匹配:

.:  匹配任意单个字符;

[]: 匹配指定范围内的任意单个字符

[^]:匹配指定范围外的任意单个字符

         [:digit:]、[:lower:]、[:upper:]、[:alpha:]、[:alnum:]、[:punct:]、[:space:]

匹配次数

用在要指定次数的字符后面,用于指定前面的字符要出现的次数;

*:匹配前面的字符任意次(有可能是0次);

                    例如: grep "x*y" 

                        abxy

                        xay

                        xxxxxxy

 贪婪模式:转义字符必须加单引号,否则不生效

 .*:任意长度的任意字符;# grep .*y 1.log

\?:匹配其前面的字符0或1次;即前面的可有可无;#   grep 'x\?y' 1.log

\+:匹配其前面的字符至少1次;# grep 'x\+y' 1.log

\{m\}:匹配前面的字符m次;# grep 'x\{2\}y' 1.log

\{m,n\}:匹配前面的字符至少m次,至多n次;# grep   'x\{2,4\}y' 1.log

\{0,n\}:匹配前面的字符至多n次;# grep 'x\{0,2\}y' 1.log

\{m,\}:匹配前面的字符至少m次;# grep 'x\{1,\}y' 1.log

 位置锚定

 ^:行首锚定;用于模式的最左侧;# cat   /etc/passwd |grep ^root

 $:行尾锚定;用于模式的最右侧;# cat /etc/passwd |grep /bin/bash$

                ^PATTERN$: 用于模式匹配整行;# grep ^xxy$ 1.log

                    ^$: 空行;grep ^$ 1.log

                    ^[[:space:]]*$:     # grep ^[[:space:]]*$ 1.log

 \< 或 \b:词首锚定;用于单词模式的左侧;cat /etc/passwd   |grep '\<r'

\> 或 \b:词尾锚定;用于单词模式的右侧;cat /etc/passwd   |grep '\>r'

                \<PATTERN\>:匹配整个单词;cat /etc/passwd |grep '\<root\>'

 分组:

 \(\):将一个或多个字符捆绑在一起,当作一个整体进行处理;# grep '\(xy\)' 1.log

                    \(xy\)*ab   : # grep '\(xx\)*y' 1.log

 Note: 分组括号中的模式匹配到的内容会被正则表达式引擎记录于内部的变量中,这些变量的命名方式为: \1, \2, \3, …

       \1: 从左侧起,第一个左括号以及与之匹配右括号之间的模式所匹配到的字符;

                        \(ab\+\(xy\)*\):

                            \1: ab\+\(xy\)*

                            \2: xy

后向引用:

 引用前面的分组括号中的模式所匹配字符,(而非模式本身)

 基本练习:

1.搜索和寻找文件

查找一个文件或者某些包含特定关键字的文件。

比如,在Centos7中,默认没有安装ifconfig命令,那么在挂载好CDROM后,需要找出ifconfig命令的包装包(ifconfig 包含在net-tools安装包中),再利用rpm –ivh进行安装:

[root@192 Packages]# ll |grep –i net-tools
-r--r--r--. 2 root root    311020 7月   4 2014 net-tools-2.0-0.17.20131004git.el7.x86_64.rpm

2.搜索并过滤文件

在示例文件1.log中,有大量的空行,把文件内所有的空行删除并另存为2.log文件。

[root@192 scripts]# grep -v ^[[:space:]]*$ 1.log  >2.log

3显示/proc/meminfo文件中以大小s开头的行;(要求:使用两种方式)

# grep -i ^s /proc/meminfo
# grep ^[Ss]  /proc/meminfo

4显示/etc/passwd文件中不以/bin/bash结尾的行;

#grep -v /bin/bash$ /etc/passwd

5显示/etc/passwd文件中ID号最大的用户的用户名;

# sort -t: -k3 -n /etc/passwd |tail -1|cut -f1 -d:

6如果用户root存在,显示其默认的shell程序;

# id root &> /dev/null && grep "^root\>" /etc/passwd | cut -d: -f7

7找出/etc/passwd中的两位或三位数;

 # grep "\<[0-9]\{2,3\}\>" /etc/passwd

8显示/etc/rc.d/rc.sysinit文件中,至少以一个空白字符开头的且后面存非空白字符的行;

# grep "^[[:space:]]\+[^[:space:]]" /etc/grub2.cfg

9找出"netstat -tan"命令的结果中以'LISTEN'后跟0、1或多个空白字符结尾的行;

# netstat -tan | grep "LISTEN[[:space:]]*$"

10添加用户bash、testbash、basher以及nologin(其shell为/sbin/nologin);而后找出/etc/passwd文件中用户名同shell名的行;

# grep "^\([[:alnum:]]\+\>\).*\1$" /etc/passwd

11获取当前IP地址,只输出IP地址信息(这道题我做了很多次,一次比一比精简,虽然可能在CentOS6上不通用,但是多思考一下总是对的):

ifconfig |grep ^[[:space:]]*inet |tr -s ' ' |cut -d' ' -f3 |grep ^[1-2]|grep -v 127
ifconfig |grep -A1 eno |grep '^[[:space:]]\+inet' |tr -s ' '|cut -d' ' -f3
ifconfig |grep inet |tr -s ' ' |cut -d' ' -f3 |grep ^[1-2]|grep -v 127
ifconfig |grep -A 1 eno |grep inet |tr -s ' '|cut -f3 -d' '
ifconfig |grep inet.*255$|tr -s ' '|cut -f3 -d' '

    实例练习:

        1、写一个脚本,实现如下功能

            如果user1用户存在,就显示其存在,否则添加之,并显示添加的用户的id号等信息;

 #!/bin/bash
 id user1 &> /dev/null && echo "user1 exists." || useradd user1
 id user1

 

        2、写一个脚本,完成如下功能

            如果root用户登录了当前系统,就显示root用户在线;否则说明其未登录;

# w |grep ^FZ &> /dev/null && echo "Yes" || echo "NO"

2.2 egrep及扩展的正则表达式

      egrep = grep -E

      egrep [OPTIONS] PATTERN [FILE…]

扩展正则表达式的元字符:

举例

字符匹配:

 

.

[]

[^]

次数匹配:

*

?:0或1次;

+:1次或多次;

{m}:匹配m次;

{m,n}:至少m,至多n次;

锚定:

^

$

\<,\b

\>,\b

分组:

()

后向引用:

\1,\2,…

或者:

a|b

C|cat:C或cat

 基本练习:

            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

2.3 fgrep不支持正则表达式搜索

fgrep只搜索字符串而不是搜索匹配表达式的模式。

 例如,当在用grep –r 搜索/etc及其子目录中所有包括.bash的文件内容时,其中的.则不会被当成正则表达式中所表示的“任意单个字符”

[root@192 ~]# fgrep -r .bashrc /etc/
/etc/profile.d/256term.sh:# Set this variable in your local shell config (such as ~/.bashrc)
/etc/bash_completion.d/git:#    2) Add the following line to your .bashrc/.zshrc:
/etc/skel/.bash_profile:if [ -f ~/.bashrc ]; then
/etc/skel/.bash_profile:    . ~/.bashrc
/etc/skel/.bashrc:# .bashrc

 

 

原创文章,作者:FZ,如若转载,请注明出处:http://www.178linux.com/18545

(0)
FZFZ
上一篇 2016-06-22
下一篇 2016-06-22

相关推荐

  • linux中用ACL实现灵活的权限管理

    ACL是什么?? ACL英文原意是Access Control List(访问控制列表).它能够实现灵活的权限管理,除了文件的所有者,所属组和其他人,设置相应的权限外,ACL允许你给任何用户或是用户组设置任何文件/目录的访问权限(注意的是有些不支持数字模式的权限给定) ACL有什么用?? 作为UGO权限管理的补充,acl有GUO办不到或者是难以办到的功能 &…

    Linux干货 2016-08-05
  • Linux高级文件系统管理

                                          &n…

    系统运维 2016-09-06
  • btr文件系统与网络基础

    btrfs文件系统技术预览版Btrfs (B-tree, Butter FS, Better FS), GPL, Oracle, 2007, CoW核心特性:多物理卷支持:btrfs可由多个底层物理卷组成;支持RAID,以及联机“添加”、“移除”,“修改”写时复制更新机制(CoW):复制、更新及替换指针,而非“就地”更新数据及元数据校验码:checksum子…

    Linux干货 2016-09-02
  • grep、正则表达式

    grep、正则表达式 grep:文本过滤(模式:pattern)工具 作用:文本搜索工具,根据用户指定的“模式”对目标文本逐行进行匹配检查;打印匹配到的行。 模式:由正则表达式字符及文本字符所编写的过滤条件。 正则表达式:由一类特殊字符及文本所编写的模式,其中有些字符不表示字符字面意义,而表示控制或通配的功能。 正则表达式分为两类:基本正则表达式、扩展正则表…

    Linux干货 2017-04-06
  • 磁盘分区相关知识

    磁盘分区相关知识 使用磁盘分区的过程设备识别→设备分区→创建文件系统→标记文件系统→在/etc/fstab文件中创建条目→挂载新的文件系统 分区不是必须的,但是分区是必要的:优化I/O性能实现磁盘空间配额限制提高修复速度隔离系统和程序安装多个OS采用不同文件系统 不重启激活新添加的磁盘:echo “- – -” > …

    Linux干货 2017-08-20
  • N26第三周博客作业

    1、列出当前系统上所有已经登录的用户的用户名,注意:同一个用户登录多次,则只显示一次即可。    who | cut -d' ' -f1 | sort -u 2、取出最后登录到当前系统的用户的相关信息。    last | head -1   3、取出当前系统上被用户当作其默认s…

    Linux干货 2017-02-03

评论列表(1条)

  • stanley
    stanley 2016-06-22 15:40

    赞,已置顶