删除匹配的第n行,直到空行的awk / SED / grep的 [英] Delete matching nth line until blank line in awk/sed/grep

查看:783
本文介绍了删除匹配的第n行,直到空行的awk / SED / grep的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从比赛中删除一个文件中第n个匹配的行到下一个空行(即开始第n匹配空行分隔符的文本中一个模块)。

I need to delete the nth matching line in a file from the match up to the next blank line (i.e. one chunk of blank line delimited text starting with the nth match).

推荐答案

这将删除文本块启动,并以一个空行开始的第四个空行结束。它还会删除那些划定线路。

This will delete a chunk of text that starts and ends with a blank line starting with the fourth blank line. It also deletes those delimiting lines.

sed -n '/^$/!{p;b};H;x;/^\(\n[^\n]*\)\{4\}/{:a;n;/^$/!ba;d};x;p' inputfile

更改第一个 / ^ $ / 来改变开始的比赛。更改第二个改变比赛结束

Change the first /^$/ to change the start match. Change the second one to change the end match.

鉴于这种输入:

aaa
---
bbb
---
ccc
---
ddd delete me
eee delete me
===
fff
---
ggg

该版本的命令:

sed -n '/^---$/!{p;b};H;x;/^\(\n[^\n]*\)\{3\}/{:a;n;/^===$/!ba;d};x;p' inputfile

会给这个作为结果:

would give this as the result:

aaa
---
bbb
---
ccc
fff
---
ggg

编辑:

我删除了上述 SED 命令外来 B 指令。

I removed an extraneous b instruction from the sed commands above.

下面是一个注释版本:

sed -n '      # don't print by default
  /^---$/!{   # if the input line doesn't match the begin block marker
    p;        # print it
    b};       # branch to end of script and start processing next input line
  H;          # line matches begin mark, append to hold space
  x;          # swap pattern space and hold space
  /^\(\n[^\n]*\)\{3\}/{    # if what was in hold consists of 3 lines
                           # in other words, 3 copies of the begin marker
    :a;       # label a
    n;        # read the next line
    /^===$/!ba;    # if it's not the end of block marker, branch to :a
    d};       # otherwise, delete it, d branches to the end automatically
  x;          # swap pattern space and hold space
  p;          # print the line (it's outside the block we're looking for)
' inputfile   # end of script, name of input file

任何明确的模式应该工作的开始和结束标记。它们可以是相同或不同的

Any unambiguous pattern should work for the begin and end markers. They can be the same or different.

这篇关于删除匹配的第n行,直到空行的awk / SED / grep的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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