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

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...