zoukankan      html  css  js  c++  java
  • Shell 文本处理三剑客之grep

    grep

    ♦参数

    -E,--extended-regexp              模式是扩展正则表达式
    -i,--ignore-case                  忽略大小写
    -n,--line-number                  打印行号
    -v,--invert-match                 打印不匹配的行
    -o,--only-matching                只打印匹配的内容
    -m,--max-count=NUM               输出匹配的结果 num 数
    -c,--count                        只打印每个文件匹配的行数
    -r,--recursive                    递归目录 
    -w,--word-regexp                  模式匹配整个单词 
    --include=FILE_PATTERN             只检索匹配的文件

     ♦示例

    1.过滤b文件中与a文件相同的行

    [root@gitlab grep]# cat a.txt 
    12345
    54321
    [root@gitlab grep]# cat b.txt 
    12345
    678910
    12345
    [root@gitlab grep]# grep -f a.txt b.txt 
    12345
    12345
    [root@gitlab grep]# grep -f b.txt a.txt 
    12345
    [root@gitlab grep]# 

    2.过滤b文件中与a文件不同的行

    [root@gitlab grep]# grep -v -f a.txt b.txt 
    678910
    

    3.匹配出去空行和以#开头的行

    [root@gitlab grep]# grep -E -v "^$|^#" /etc/fstab 
    

     4.精确匹配

    [root@gitlab grep]# echo ” this is a test“ | egrep -w -o 'is'
    is

    -w 匹配到整个单词 -o 输出匹配到的单词

    5.输出匹配的前五个结果

    [root@gitlab grep]# seq 1 20 | grep -E -m 5 [0-9]{2}
    10
    11
    12
    13
    14

     6.统计匹配多少行

    [root@gitlab grep]# seq 1 20 | grep -c -E '[0-9]{2}'
    11
    

     7.匹配以b开头的行

    # echo "a bc de" |xargs -n1 |grep '^b'
    

     8.匹配de字符结尾的行,并输出匹配的行号

    echo "a ab abc abcd abcde" |xargs -n1 |grep -n 'de$'
    

     9.

    →递归搜索/etc目录下包含UUID的所有文件

    [root@gitlab grep]# grep -r 'UUID' /etc --include *

    →递归搜索/etc 目录下包含 ip 的 conf 后缀文件

    [root@gitlab grep]# grep -r '192.167.1.1' /etc --include *.conf
    /etc/ip.conf:192.167.1.1
    

     10.匹配所有IP

    [root@gitlab shell]# ifconfig |grep -E -w -o "[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}"
    

     11.杂谈

    grep [^#] /data/zabbix/etc/zabbix_server.conf
    匹配除了#以外任意的字符
    grep ^[^#] /data/zabbix/etc/zabbix_server.conf
    过滤出来不是以#开头的行
    

     

  • 相关阅读:
    统计数据库表中记录数
    在水晶报表中写一个条件判断语句
    数据库范式
    动态控件的新思路
    连续打印问题的解决
    水晶报表中测试纸张的margins
    向报表中传递参数
    JS实现页面跳转
    在dos下访问ntfs
    时间和字符混合处理
  • 原文地址:https://www.cnblogs.com/charon2/p/10552091.html
Copyright © 2011-2022 走看看