• grep 举例

    post by bgaidu / 2008-4-18 21:41 Friday
    grep '[A-Z]' list Lines from list containing a capital letter

    grep '[0-9]' data Lines from data containing a number

    grep '[A-Z]...[0-9]' list Lines from list containing five-character patterns that start with a capital letter and end with a digit

    grep '\.pic$' filelist Lines from filelist that end in .pic

    $ grep shell *
    cmdfiles:shell that enables sophisticated
    ed.cmd:files, and is independent of the shell.
    ed.cmd:to the shell, just type in a q.
    grep.cmd:occurrence of the word shell:
    grep.cmd:$ grep shell *
    grep.cmd:every use of the word shell.
    $

    -i表示忽略大小写
    grep –i 'the' intro
    -v表示查找不包含此字符串的行
    $ grep -v 'UNIX' intro Print all lines that don't contain UNIX
    Thompson and Dennis Ritchie at Bell Laboratories
    in the late 1960s. One of the primary goals in
    environment that promoted efficient program
    development.
    $
    -l表示列出包含此字符串的文件名 $ grep -l 'Move_history' *.c List the files that contain Move_history
    exec.c
    makemove.c
    testch.c
    $
    $ grep -l 'Move_history' *.c | wc -l
    3
    $
    -n打印所包含字符串的行数
    $ grep -n 'Move_history' testch.c Precede matches with line numbers
    13:GLOBAL MOVE Move_history[100] = {0};
    197: Move_history[Number_half_moves-1].from = move.from;
    198: Move_history[Number_half_moves-1].to = move.to;
    $



    grep(全局正则表达式版本)允许对文本文件进行模式查找,grep支持基本正则表达式,也支持其扩展集。
    grep有三种变形:
        grep 标准grep命令
        egrep 扩展grep命令,支持基本及扩展的正则表达式,但不支持\q模式范围的应用
        fgrep 快速grep命令,允许查找字符串而不是一个模式,不要误解fast,其实和grep速度相当
    grep的一般格式:
        grep [选项] 基本正则表达式 [文件]   这里的基本正则表达式可为字符
    使用双引号:
        字符串参数最好使用双引号扩起来,一是以防被误解为shell命令,二是可以用来查找多个单词组成的字符串,在调用变量的时候也要使用双引号,比如grep "$MYVAR",否则无结果,在调用模式匹配是,应使用单引号

    grep的选项:
        -c 只输出匹配行的计数,比如grep -c "test" *.txt,将显示4,则说明包含test的有4行
        -i 不区分大小写(只适用于单字符),比如grep -i "Bank" *.c等同于grep -i "bank" *.c
        -h 查询多文件时不显示文件名
        -l 查询多文件时只输出包含匹配字符的文件名
        -n 显示匹配行及行号,在显示出内容的每行前面会显示行数
        -s 不显示不存在或无匹配文本的错误信息
        -v 显示不包含匹配文本的所有行,grep -v "test" abc.txt,将显示不包含"test"的行内容
        -w 以单词为单位进行匹配
        -E 允许使用扩展模式匹配

    grep和正则表达式:
        使用正则表达式最好使用单引号括起来,避免参数被做为shell命令执行
        模式范围: grep '48[a-z]' *.txt
        不匹配行首: grep '^[^48]' *.txt 查找行首不是48的行内容
        设置大小写: grep '[Ss]ept' *.txt 查找Sept和sept内容
        匹配任意字符: grep 'K...D' *.txt     grep '[A-Z][A-Z]..C' *.txt
         "与"和"或": grep -E '219|216' *.txt 查找包含219或者216的行内容
         空行: grep '^$' *.txt
         类名: [[:upper:]] -> [A-Z]        [[:lower:]]   ->    [a-z]
              [[:digit:]] ->   [0-9]         [[:alnum:]]   -> [0-9a-zA-Z]
               [[:space:]] -> 空格或者tab键   [[:alpha:]] ->   [a-zA-Z]
            grep '5[[:upper:]]' *.txt 等同于 grep '5[A-Z]' *.txt
         列出所有的目录   ls -l |grep '^d'      
        列出所有的非目录   ls -l |grep '^[^d]' 或 ls -l |grep -v '^d'


    
    您对本文的评分:
    当前平均分: 0.0(0 次打分)

    引用地址:

    发表评论: