仅删除第一次和第三次出现的块的内容 [英] Remove the contents of block only 1st and 3rd occurence

查看:91
本文介绍了仅删除第一次和第三次出现的块的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下sed删除了{content-start}和{content-end}之间所有出现的块,但只想删除第1和第3块,而不是第2块.

Below sed removes all occurrences of blocks between {content-start} and {content-end}, but want to remove only 1st and 3rd blocks and not 2nd block.

sed -ie '/{content-start.*}/,/{content-end}/d' test.txt

test.txt:

{content-start}
abc1
def1
ghi1
{content-end}
{content-start}
abc2
def2
ghi2
{content-end}
{content-start}
abc3
def3
ghi3
{content-end}

推荐答案

sed用于单个行上的简单替换,即s/old/new/,全部.对于其他任何事情,您都应该使用awk:

sed is for simple subsitutions on individual lines, i.e. s/old/new/, that is all. For anything else you should be using awk:

$ awk '{rec = rec $0 ORS} /{content-end}/{if (++cnt == 2) printf "%s", rec; rec=""}' file
{content-start}
abc2
def2
ghi2
{content-end}

或者如果您想对单独的行进行任何操作,则将记录的每一行保存在数组中,而不是将整个记录保存为字符串:

or if you're ever going to want to do anything with individual lines then save each line of the record in an array rather than saving the whole record as a string:

{ rec[++numLines] = $0 }
/{content-end}/ {
    if ( ++cnt == 2 ) {
        for (lineNr=1; lineNr<=numLines; lineNr++) {
            print rec[lineNr]
        }
    }
    delete rec
    numLines = 0
}

以上内容适用于任何UNIX系统上任何shell中的任何awk,并且在/当您的需求发生变化时,可以轻松地进行增强.

The above will work with any awk in any shell on any UNIX system and is trivial to enhance if/when your requirements change.

这篇关于仅删除第一次和第三次出现的块的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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