对于包含模式的行,删除前 n1 行和后 n2 行 [英] Delete n1 previous lines and n2 lines following with respect to a line containing a pattern

查看:17
本文介绍了对于包含模式的行,删除前 n1 行和后 n2 行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sed -e '/XXXX/,+4d' fv.out

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

I have to find a particular pattern in a file and delete 5 lines above and 4 lines below it simultaneously. I found out that the line above removes the line containing the pattern and four lines below it.

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

在 sed 手册中给出了 ~ 代表后面跟着模式的行.但是当我尝试时,它是删除了模式后面的行.

In sed manual it was given that ~ represents the lines which is followed by the pattern. But when i tried it, it was the lines following the pattern that was deleted.

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

So, how do I delete 5 lines above and 4 lines below a line containing the pattern simultaneously?

推荐答案

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

One way using sed, assuming that the patterns are not close enough each other:

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.
    /(
[^
]*){6}/ {

        ## Delete the first '
' automatically added by previous 'H' command.
        s/^
//
        ## Print until first '
'.
        P   
        ## Delete data printed just before.
        s/[^
]*//
        ## 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/^
//
        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

这篇关于对于包含模式的行,删除前 n1 行和后 n2 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆