美文网首页
图解sed的hold space和pattern space的交

图解sed的hold space和pattern space的交

作者: ape_caesar | 来源:发表于2019-01-09 11:06 被阅读0次

    代码grep3line.sh

    以下脚本的功能是查找文本的匹配字符串,然后打印匹配字符串所在行的前一行,匹配字符串所在行,匹配字符串所在行后一行。然后以___(三个下划线)结尾

    #!/bin/sh
    # grep3 - prints out three lines around pattern
    # if there is only one argument, exit
    
    case $# in 
        1);;
        *) echo "Usage: $0 pattern";exit;;
    esac;
    # I hope the argument doesn't contain a /
    # if it does, sed will complain
    
    # use sed -n to disable printing 
    # unless we ask for it
    sed -n '
    '/$1/' !{
        #no match - put the current line in the hold buffer
        x
        # delete the old one, which is 
        # now in the pattern buffer
        d
    }
    '/$1/' {
        # a match - get last line
        x
        # print it
        p
        # get the original line back
        x
        # print it
        p
        # get the next line 
        n
        # print it
        p
        # now add three dashes as a marker
        a\
    ---
        # now put this line into the hold buffer
        x
    }'
    

    执行脚本

    echo -e '1\n2\n3\n4' | ./grep3line.sh 2
    # 输出
    1
    2
    3
    ___
    

    图解过程

    图解过程.png

    相关文章

      网友评论

          本文标题:图解sed的hold space和pattern space的交

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