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 15:39
下一篇 2016-06-22 15:40

相关推荐

  • 优云运维安全专家实践:使用802.1X+FreeRadius+LDAP实现网络准入方案

    本文,将为大家分享运维前沿在网络准入管理方面的实践经验。 网络准入业界常用方案 为了保证网络资源的安全,拒绝非法入侵,现代IT网络总需要一定的网络准入方案,而目前业界常用的网络准入方案有: 而今天给大家介绍的802.1X+FreeRadius+LDAP网络准入方案,则避免了上述方案中的缺点,是一套低成本,控制能力强,符合行业标准的一套网络准入认证体系。 什么…

    安全运维 2016-07-10
  • httpd应用举例

    应用举例1、基于用户和组认证的方式访问ftp         1、编辑配置文件/etc/httpd/conf/httpd.conf,并使用httpd -t 检查语法,并systemctl reload httpd       &n…

    Linux干货 2016-10-23
  • 软件包管理工具—yum命令总结

    描述: YUM: Yellowdog Update Modifier, rpm的前端程序,用来解决软件包相关依赖性,可以在多个库之间定位软件包,实现查询、安装、升级、删除等功能 说明: yum repository: yum repo,存储了众多rpm包,以及包的相关的元数据文件(放置于特定目录repodata下) 文件服务器: ftp:// http://…

    Linux干货 2016-08-29
  • N22-第四周

    1、复制/etc/skel目录到/home/tuser1,要求/home/tuser1及其内部文件的属组和其它用户均没有任何访问权限。 ~]# cp -r /etc/skel /home/tuser1~]# ll -d /home/tuser1drwxr-xr-x. 3 root root 74 Aug 31 10:13 /home/tuser1~]# ch…

    Linux干货 2016-09-07
  • 10月18日作业–hash,history

    1 生产环境发现一台服务器系统时间产生偏差,造成服务异常,请帮忙校正。 1、使用ntpdate对时间进行同步,然后hwclock -w;并再建立Crontab每小时进行一次时间同步。 2 生产有一个数据同步脚本需要执行很长时间,怎样做到无人值守,在管理工具退出的情况下,脚本依然能正常运行。 1、载光盘 2、进入/mnt/Packages 安装共享screen…

    Linux干货 2016-10-19
  • Linux网络属性配置

      一台主机想要接入网络就必须配置相关的网络属性,如:主机名、IP地址、子网掩码、网关、DNS等,下面总结了网络属性的配置方法。 一、配置主机名   主机名配置有两种方式:命令和配置文件。   1、hostname命令    可以使用hostname命令来配置主机名,不过这样配置的主机名不会永久生效,只能在当…

    Linux干货 2016-01-06

评论列表(1条)

  • stanley
    stanley 2016-06-22 15:40

    赞,已置顶