sed 从特定匹配行中删除一系列行直到特定匹配行(不包括最后一行) [英] Sed to delete a range of lines from a specific match line TILL a specific match line (not including last line)

查看:75
本文介绍了sed 从特定匹配行中删除一系列行直到特定匹配行(不包括最后一行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通读了论坛以寻找如何解决我的问题的线索,但没有任何相关主题可供我使用,因为我的编程知识有限,可以应用于我的特定问题.

I read through the forum for clues how to solve my problem, but none of the related threads are useable for me, with limited programming knowledge, to apply to my specific problem.

我的问题是:我需要删除在我的文件中聚集的垃圾行,但是在可用行的集群之间.我搜索了 sed 手册和其他有关删除匹配模式范围的信息来源,但他们只提到删除 UNTIL 匹配模式,而不是 TILL.

My problem is this: I need to get rid of garbage lines that are clustered throughout my file, but are in between clusters of useable lines. I searched the sed manual and other informative sources about deleting ranges that match patterns, but they only mention to delete UNTIL match pattern, not TILL.

现在我想指定一个范围,sed 删除从与模式行匹配的第一行开始到与其他模式匹配的行的行.此外,sed 需要识别存在于行尾的模式.

Now I would like to specify a range for which sed deletes lines starting from the first line that matches the pattern line till the line that matches the other pattern. Furthermore, sed needs to recognize the patterns that exists at the end of the lines.

例如:

line 1
blah blah 1
blah blah 2
blah blah 3
blah blah 4
line 2
line 3

结果必须是:

line 1
blah blah 1
line 2
line 3

请注意 line 和 line 2 之间的多行.虽然 blah blah 1 需要保留,但其他 3 需要删除.

Please note the multiple lines between line and and line 2. While blah blah 1 needs to stay, the other 3 need to be deleted.

谢谢!

推荐答案

试试这个

sed -n '/line 1/{;p;n;p;};/line 2/,$p'  sedTest1.txt

#output
line 1
blah blah 1
line 2
line 3

Sed 解构:

 sed -n '/line 1/{;p;n;p;};/line 2/,$p'  sedTest1.txt
     |    |        |        |      |||-> print the range
     |    |        |        |      ||-> til end of file (the '$' char)
     |    |        |        |      |-> range operator (i.e. start,end)
     |    |        |        |-> beginning of range to watch for and print
     |    |        |-> now print line, get 'n'ext, print that line 
     |    |-> match the line with text 'line 1'
     |-> don't print every line, only ones flagged with 'p'

从下往上阅读.

此外,由于您的数据是一个样本,并且您将其称为垃圾行,因此可能没有这么简单.您需要阅读 sed 教程以加快速度.

Also, as your data is a sample, AND you refer to it as garbage lines, it may not be this simple. You'll need to look through sed tutorials to get up to speed.

我希望这会有所帮助.

这篇关于sed 从特定匹配行中删除一系列行直到特定匹配行(不包括最后一行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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