bash – 相对于包含模式的行,删除n1个前面的行和n2行

前端之家收集整理的这篇文章主要介绍了bash – 相对于包含模式的行,删除n1个前面的行和n2行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
sed -e '/XXXX/,+4d' fv.out

我必须在文件中找到一个特定的模式,同时删除上面的5行和下面的4行.我发现上面的行删除了包含模式的行和它下面的四行.

sed -e '/XXXX/,~5d' fv.out

在sed手册中,给出了〜表示图案所遵循的线条.但是,当我尝试它时,它是删除模式后面的行.

那么,如何同时删除包含该模式的行下面的5行和4行?

使用sed的一种方法,假设模式彼此不够接近:

script.sed的内容

## If line doesn't match the pattern...
/pattern/ ! { 

    ## Append line to 'hold space'.
    H   

    ## Copy content of 'hold space' to 'pattern space' to work with it.
    g   

    ## If there are more than 5 lines saved,print and remove the first
    ## one. It's like a FIFO.
    /\(\n[^\n]*\)\{6\}/ {

        ## Delete the first '\n' automatically added by prevIoUs 'H' command.
        s/^\n//
        ## Print until first '\n'.
        P   
        ## Delete data printed just before.
        s/[^\n]*//
        ## Save updated content to 'hold space'.
        h   
    } 

### Added to fix an error pointed out by potong in comments.
### =======================================================
    ## If last line,print lines left in 'hold space'.
    ${ 
        x   
        s/^\n//
        p   
    } 
### =======================================================


    ## Read next line.
    b   
}

## If line matches the pattern...
/pattern/ {

    ## Remove all content of 'hold space'. It has the five prevIoUs
    ## lines,which won't be printed.
    x   
    s/^.*$//
    x   

    ## Read next four lines and append them to 'pattern space'.
    N ; N ; N ; N 

    ## Delete all.
    s/^.*$//
}

运行如下:

sed -nf script.sed infile

猜你在找的Bash相关文章