从sed/START/,/END/中排除第一行和最后一行 [英] excluding first and last lines from sed /START/,/END/

查看:336
本文介绍了从sed/START/,/END/中排除第一行和最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑输入:

=sec1=
some-line
some-other-line

foo
bar=baz

=sec2=
c=baz

如果我只想处理= sec1 =,我可以通过以下方式注释掉该部分:

If I wish to process only =sec1= I can for example comment out the section by:

sed -e '/=sec1=/,/=[a-z]*=/s:^:#:' < input

...好吧,差不多.

... well, almost.

这将注释行,包括"= sec1 ="和"= sec2 ="的行,结果将如下所示:

This will comment the lines including "=sec1=" and "=sec2=" lines, and the result will be something like:

#=sec1=
#some-line
#some-other-line
#
#foo
#bar=baz
#
#=sec2=
c=baz

我的问题是:从sed的/START/,/END/范围中排除开始和结束行的最简单方法是什么?

My question is: What is the easiest way to exclude the start and end lines from a /START/,/END/ range in sed?

我知道,在很多情况下,改进s :::爪子可以在这种特定情况下提供解决方案,但是我在这里寻求通用解决方案.

I know that for many cases refinement of the "s:::" claws can give solution in this specific case, but I am after the generic solution here.

在布鲁斯·巴内特(Bruce Barnett)写道:" Sed-简介和教程中:稍后我将向您展示如何将命令限制为最多,但不包括包含指定模式的行.",但我无法找到他实际显示此位置的地方.

In "Sed - An Introduction and Tutorial" Bruce Barnett writes: "I will show you later how to restrict a command up to, but not including the line containing the specified pattern.", but I was not able to find where he actually show this.

在Eric Pement编写的"有用的SED单行脚本"中,我可以仅找到包含性的示例:

In the "USEFUL ONE-LINE SCRIPTS FOR SED" Compiled by Eric Pement, I could find only the inclusive example:

# print section of file between two regular expressions (inclusive)
sed -n '/Iowa/,/Montana/p'             # case sensitive

推荐答案

这应该可以解决问题:

sed -e '/=sec1=/,/=sec2=/ { /=sec1=/b; /=sec2=/b; s/^/#/ }' < input

这将在sec1和sec2(包括sec1和sec2)之间进行匹配,然后仅使用b命令跳过第一行和最后一行.这样将在sec1和sec2(不包括)之间保留所需的行,并且s命令添加注释符号.

This matches between sec1 and sec2 inclusively and then just skips the first and last line with the b command. This leaves the desired lines between sec1 and sec2 (exclusive), and the s command adds the comment sign.

不幸的是,您确实需要重复正则表达式以匹配定界符.据我所知,没有更好的方法可以做到这一点.至少您可以保持正则表达式干净,即使它们被使用了两次.

Unfortunately, you do need to repeat the regexps for matching the delimiters. As far as I know there's no better way to do this. At least you can keep the regexps clean, even though they're used twice.

此内容摘录自 SED常见问题解答:如何解决RE1和RE1之间的所有界限RE2,不包括行本身吗?

这篇关于从sed/START/,/END/中排除第一行和最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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