zoukankan      html  css  js  c++  java
  • linux中grep命令

    grep [option] "pattern" 文件名
    grep "root" /etc/passwd 过滤带有root 字符

    正则表达式元字符
    1匹配单个字符的元字符
    . 表示任意单个字符
    [root@localhost ~]# grep "r..t" /etc/passwd
    [abc] 或者
    [root@localhost ~]# grep "r[aA]t" /tmp/1.txt

    - 连续的字符范围
    [a-z] [A-Z] [a-zA-Z] [0-9] [a-zA-Z0-9]

    [root@localhost ~]# grep "r[A-Z]t" /tmp/1.txt
    rAt
    [root@localhost ~]# grep "r[0-9]t" /tmp/1.txt
    r8t
    [root@localhost ~]# grep "r[a-zA-Z0-9]t" /tmp/1.txt
    r8t
    rAt

    ^ 取反
    [^a-z]
    [root@localhost ~]# grep "r[^0-9]t" /tmp/1.txt
    rAt


    特殊字符集:
    [[:punct:]] 任意单个标
    [root@localhost ~]# grep -En "r[[:punct:]]t" /tmp/1.txt
    11:r,t
    12:r?t
    13:r"t"

    [[:space:]]任意单个空白字符
    [root@localhost ~]# grep -En "r[[:space:]]t" /tmp/1.txt
    14:r t


    2 匹配字符出现的位置
    1) ^string 以string 开头
    2)^[rbh] 查找以rbh 开头-----取反 ^[^rbh]
    [root@localhost ~]# grep "^[^rbh]" /etc/passwd

    3) string& 以string 结尾
    [root@localhost ~]# grep "bash&" /etc/passwd
    [root@localhost ~]# grep "nologin&" /etc/passwd | wc -l

    4) ^& 空行
    [root@localhost ~]# grep "^&" /etc/fstab | wc -l

    显示/etc下的目录名
    [root@localhost ~]# ls -l /etc/ | grep "^d"


    3 匹配字符出现的次数

    * 匹配前一个字符出现的任意次 ab*: a ab abb abbb
    [root@localhost ~]# grep "ab*" /tmp/2.txt
    .* 任意字符

    ? 前一个字符最多出现一次 最少出现0次或一次
    * 0 or 多次
    + one or more times.(一次或者多次)
    {n} 字符精确出现几次
    {n,} 最少n次 多了不限
    {,m} 最多m次
    {n,m} 最少n次 做多m次

    ? 0次或者1次 可有可无
    [root@localhost ~]# grep "ab?" /tmp/2.txt

    + 1次或者多次 最少1次
    [root@localhost ~]# grep "ab+" /tmp/2.txt

    {2} 精确匹配2次
    [root@localhost ~]# grep "ab{2}" /tmp/2.txt

    {2,5} 最少2次 最多5次
    [root@localhost ~]# grep "ab{2,5}" /tmp/2.txt

    {2,} 最少2次
    [root@localhost ~]# grep "ab{2,}" /tmp/2.txt

    分组 (ab)+
    [root@localhost ~]# grep "(ab){2,}" /usr/share/dict/words


    option选项:
    1) -i 忽略大小写
    [root@localhost ~]# grep -i "^r" /tmp/1.txt
    2) -o 仅显示符合正则表达式的内容,不再显示整行
    xpl@localhost ~]$ grep -o "r..t" /etc/passwd
    3) -v 反向过滤
    [root@localhost ~]# grep -v "^#" /etc/fstab
    4) -e 根据多个选项过滤文本
    [root@localhost ~]# grep -e "^&" -e "^#" /etc/fstab
    [root@localhost ~]# grep -v -e "^&" -e "^#" /etc/fstab 不显示
    5)-E 支持扩展正则表达式
    [root@localhost ~]# grep -E "(ab){2,}" /usr/share/dict/words

    cpu信息
    [root@localhost ~]# cat /proc/cpuinfo
    [root@localhost ~]# grep -E "vmx|svm" /proc/cpuinfo

    6) -A n 同时显示符合条件的后n行
    [root@localhost ~]# ifconfig eth0 | grep -A 2 "network"
    -B n 同时显示符合条件前n
    [root@localhost ~]# ifconfig eth0 | grep -B 2 "network"

    小胖专属学习分享
  • 相关阅读:
    iOS 地图与定位开发系列教程(一)
    opencv 之 transformation
    the brain 8.0
    vs中添加库文件WinMM.Lib
    JAVA简单性能检测
    【转帖】一套鼠标控制2台电脑
    Synergy工具一套键盘鼠标连接多台机器
    文件夹下所有文件及子文件夹将文件名小写
    捕捉Facebook Like的数据
    按键精灵的网页自动化测试
  • 原文地址:https://www.cnblogs.com/xpl520/p/11227732.html
Copyright © 2011-2022 走看看