加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 18:59:08 所属栏目:安全 来源:网络整理
导读:sed -e '/XXXX/,+4d' fv.out 我必须在文件中找到一个特定的模式,同时删除上面的5行和下面的4行.我发现上面的行删除了包含模式的行和它下面的四行. sed -e '/XXXX/,~5d' fv.out 在sed手册中,给出了?表示图案所遵循的线条.但是,当我尝试它时,它是删除模式后面
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读