linux基础之grep

grep: Global search REgular expression and Print out the line
作用: 文本搜索工具,根据用户指定的模式对目标文本逐行进行匹配检查,打印匹配到的行
模式: 由 正则表达式字符及文本字符所编写的过滤条件
正则表达式内容可参考博文:https://www.cnblogs.com/ckh2014/p/10758769.html

grep [OPTIONS] PATTERN [FILE...] 
    选项:
        --color=auto: 对匹配到的文本着色显示
        -v : 显示不能够被pattern匹配到的行
        -i : 忽略字符大小写
        -o : 仅显示匹配到的单词
        -q: 静默模式,不输出任何消息
        -A # :after, 后#行
        -B # :before,前#行
        -C # : context, 前后各#行
        -E ; 使用扩展的正则表达式

     grep练习:
    1. 显示/proc/meminfo 文件中以大小写s开头的行:(要求: 使用两种方式)
        # grep "^[sS]" /proc/meninfo
        # grep -i "^s" /proc/meminfo

    2. 显示/etc/passwd文件中不以/bin/bash结尾的行
        # grep -v "/bin/bash$" /etc/passwd

    3. 显示/etc/passwd 文件中ID号最大的用户的用户名
        # sort -t: -k 3 -n /etc/passwd | tail -1 | cut -d: -f1

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

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

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

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

    8.添加用户bash、testbash、basher以及nologin(其shell为/sbin/nologin):而后找出/etc/passwd文件中用户名同shell名的行
        # useradd -s /sbin/nologin nologin
        # useradd bash
        # grep "^\([[:alnum:]]\+\>\).*\1$" /etc/passwd

    9. 写一个脚本,实现如下功能
        如果user1用户存在,就显示其存在,否则添加之
        显示添加的用户的id号等信息
        #!/bin/bash
        id user1 &> /dev/null && echo "user1已存在" || useradd user1
        id user1

    10. 写一个脚本,完成如下功能
        如果root用户登录了当前系统,就显示root用户在线,否则说明其未登录
        #!/bin/bash
        w | grep "^root\>" &> /dev/null && echo "root logged" || echo "root not logged"

        egrep = grep -E
    egrep [OPTIONS] PATTERN [FILE...]
           egrep练习:
        1.显示当前系统root、centos或user1用户的默认shell和UID
            # egrep "^root|centos|user1\>" /etc/passwd | cut -d: -f3,7

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

        3.使用echo输出一绝对路径,使用egrep取出其基名
            # echo "/etc/rc.d/init.d/functions" | egrep -o "[^\/]+" | tail -1

           进一步:使用egrep取出路径的目录名,类似于dirname命令的结果
            # echo "/tmp/init.d/function/base.txt" | egrep "(\/).*\1\b"

        4.找出ifconfig命令结果中1-255之间的数值
            # ifconfig | egrep  "\<([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\>"

转载于:https://www.cnblogs.com/ckh2014/p/10758858.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值