grep

作者: 大熊的Yowai | 来源:发表于2020-05-03 23:49 被阅读0次

    grep

    基本语法:grep [选项] [--color=auto] “搜索的字符串” filename

    • -A:后面接数字,为after的意思。除了列出该行,后续的n行也列出来
    • -B:与-A相反,列出前面的n行
    • -v:不包含[搜索的字符串]的行都列出来
    • -n:显示行号
    • -i:无视字母大小写

    案例

    准备数据

    "Open Source" is a good mechanism to develop programs.
    apple is my favorite food.
    Football game is not use feet only.
    this dress doesn't fit me.
    However, this dress is about $ 3183 dollars.^M
    GNU is free air not free beer.^M
    Her hair is very beauty.^M
    I can't finish the test.^M
    Oh! The soup taste good.^M
    motorcycle is cheap than car.
    This window is clear.
    the symbol '*' is represented as start.
    Oh!
    My god!
    The gd software is a library for drafting programs.^M
    You are the best is mean you are the no. 1.
    The world <Happy> is the same with "glad".
    www.linuxidc.com I like dog.
    google is the best tools for search keyword.
    goooooogle yes!
    go! go! Let's go.
    

    查找特定字符串

    # 搜索特定字符串
    grep -n "the" regular_express.txt
    
    # 反向选择
    grep -nv "the" regular_express.txt
    
    # 不区分大小写
    grep -in "the" regular_express.txt
    

    利用[]查找集合字符

    # 1
    grep -n "t[ae]st" regular_express.txt
    
    # 2
    grep -n "oo" regular_express.txt
    
    # 3,不让「oo」前有「g」
    grep -n "[^g]oo" regular_express.txt
    
    # 4,不让「oo」前有「小写字母」
    grep -n "[^a-z]oo" regular_express.txt
    

    行首和行尾字符^$

    # the在行首
    grep -n "^the" regular_express.txt
    
    # 行首是小写字母
    grep -n "^[a-z]" regular_express.txt
    
    # 以「.」结尾的
    grep -n "\.$" regular_express.txt
    
    # 找出空白行
    grep -n "^$" regular_express.txt
    
    # 非空白行
    grep -nv "^$" regular_express.txt
    

    注意:^符号在[]内外是不同的,括号内表示「反向选择」,括号外表示「行首」

    任意一个字符和重复字符.;*

    • .:一定有一个任意字符
    • *:0到无穷多个前一个字符
    • .*:任意字符

    案例

    # 1
    grep -n "g..d" regular_express.txt
    
    # 2,注意:此处代表至少有2个o
    grep -n "ooo*" regular_express.txt
    
    # ,如果我想要字符串开头与结尾都是 g,但是两个g之间仅能存在至少一个o,亦即是 gog, goog, gooog.... 等等
    grep -n "goo*g" regular_express.txt
    
    # 找出g开头与g结尾的字符串,当中的字符可有可无
    grep -n "g.*g" regular_express.txt
    

    注意:g*代表「空字符或者一个和一个以上的g」;那么g*g就代表「g,gg,ggg等」

    限定连续字符范围{}

    注意:使用{}的时候需要加上转义符

    # 两个「o」的字符串
    grep -n "o\{2\}" regular_express.txt
    
    # 「g」后面接2-5个「o」,然后再接「g」
    grep -n "go\{2,5\}g" regular_express.txt
    
    # 2 个o 以上的 goooo....g
    grep -n "gooo*" regular_express.txt
    grep -n "go\{2,5\}" regular_express.txt
    

    相关文章

      网友评论

          本文标题:grep

          本文链接:https://www.haomeiwen.com/subject/ysusghtx.html