• grep使用常用操作十五条


    grep的全部使用语法参照grep --help
    构造数据如下:test001.txt与test002.txt

     日常工作常用的语法如下:

    一、在单个文件中查询指定字符串

    grep abc  test01/test01.txt

    查看结果如下:

     

    二、在多个文件中查找指定字符串(并支持问文件通配符)

    grep -i cdE ./*/*

     

    三、过滤多个关键字:“与”和“或”(cat+管道+grep实现)

    cat test01/test01.txt | grep ab |grep cd #同时包含ab与cd

    cat test01/test01.txt | grep -E "ab|cd"  #包含ab或cd

     

    四、查找的过程中忽略大小写(grep -i)

    grep -i abcd */*

     

    五、匹配完整的单词,而不是子串(grep -w)

    grep -w ab */*

     

    六、高亮grep的显示结果(grep --color=auto)

    alias grep='grep --color=auto'

    查看alias快捷命令是否已经添加过grep的高亮显示设置,否则添加以上的快捷指令 或直接带颜色查询

    grep --color=auto abc test01/test01.txt

     

    七、使用 -r 参数来实现递归的搜索目录(grep -r)

    不使用递归时只能查询指令的目录下的文件,使用递归时可以逐层查询

    grep -r abc ./*

     

    八、取反搜索结果(grep -v)

    grep  -v abc test01/test01.txt

     

    九、取反(多个)指定模式的匹配结果

    grep  -v -e ab -e cd  test01/test01.txt 

     

    十、只显示匹配命中的文件名称,而不显示具体匹配的内容(grep -l)

    grep -l abc test01/test01.txt

     

    十一、显示匹配的字符串位置。该位置是相对于整个文件的字节位置,不是行数(grep -b)

    grep -b abc test01/test01.txt

     

    十二、显示匹配的字符串在文件中的行数(grep -n)

    grep -n abc test01/test01.txt


    十三、显示所匹配行的前后行信息(grep -A(after),grep -B(before),grep -C(可省略after+before))

    grep -nw -A2 abcd test01/test01.txt  #-A之后n行
    grep -nw -B2 abcd test01/test01.txt  #-B之前n行
    grep -nw -C2 abcd test01/test01.txt  #-C前后n行
    grep -nw -2 abcd test01/test01.txt  #-C省略前后n行

     

    十四、正则匹配以x开头(以y结尾)的字符

    grep "^a" test01/test01.txt  #以a开头
    grep "^a..d$" test01/test01.txt  #以a开头以d结尾,中间两个字符

     

     十五、统计复合结果条件的行数(grep -c)

    grep -c ab test01/test01.txt

     

  • 相关阅读:
    (二分)进击的奶牛
    (二分)木材加工
    (简单并查集)The Suspects
    (递归)集合划分
    (简单并查集)How many tables?
    Wireless Network(并查集)
    (并查集)连通块中点的数量
    2019.04.08 电商17 购物车模型
    2019.04.08 电商 16 地址管理2
    2019.04.07 电商15 地址管理
  • 原文地址:https://www.cnblogs.com/mrwhite2020/p/16632978.html
Copyright © 2020-2023  润新知