简体   繁体   English

除了与范围结束模式匹配的行之外,如何使用 sed 打印一系列行?

[英]How to print a range of lines with sed except the one matching the range-end pattern?

I wonder if there is a sed -only way to print a range of lines, determined by patterns to be matched, except the one last line matching the end pattern.我想知道是否有一种sed方法来打印一系列行,由要匹配的模式确定,除了最后一行匹配结束模式。

Consider following example.考虑以下示例。 I have a file我有一个文件

line  1
line  2
line  3
ABC line  4
+ line  5
+ line  6
+ line  7
line  8
line  9
line 10
line 11
line 12

I want to get everything starting with ABC (including) and all the lines beginning with a + :我想得到以ABC (包括)开头的所有内容以及以+开头的所有行:

ABC line  4
+ line  5
+ line  6
+ line  7

I tried it with我试过了

sed -n '/ABC/I,/^[^+]/ p' file

but this gives one line too much:但这给出了太多的一行:

ABC line  4
+ line  5
+ line  6
+ line  7
line  8

What's the easiest way ( sed -only) to leave this last line out?什么是最简单的方法( sed )留下最后一行?

There might be better ways but I could come up with this sed 1 liner:可能有更好的方法,但我可以想出这个 sed 1 班轮:

sed -rn '/ABC/,/^[^+]/{/(ABC|^\+)/!d;p;}' file

Another sed 1 liner is另一个 sed 1 内胆是

sed -n '/ABC/,/^[^+]/{x;/^$/!p;}' file

One more sed 1 liner (and probably better)还有一个 sed 1 衬管(可能更好)

sed -n '/ABC/I{h;:A;$!n;/^+/{H;$!bA};g;p;}' file

The easiest way (I'll learn something new if anyone can solve this with one call to sed), is to add an extra sed at the end, ie最简单的方法(如果有人可以通过调用 sed 来解决这个问题,我会学到一些新东西),是在最后添加一个额外的 sed,即

sed -n '/ABC/I,/^[^+]/ p' file | sed '$d'
ABC line  4
+ line  5
+ line  6
+ line  7

Cheating, I know, but that is the beauty of the Unix pipe philosphy.作弊,我知道,但这就是 Unix pipe 哲学的美妙之处。 Keep whitiling down your data until you get what you want;-)继续减少您的数据,直到您得到您想要的;-)

I hope this helps.我希望这有帮助。

This might work for you:这可能对您有用:

 sed '/^ABC/{:a;n;/^\(ABC\|+\)/ba};d' file

EDIT: to allow adjacent ABC sections.编辑:允许相邻的ABC部分。

Well, you have selected your answer.好吧,你已经选择了你的答案。 But why aren't you using /^(ABC|\+)/ ?但是你为什么不使用/^(ABC|\+)/ Or am i mis-understanding your requirement?还是我误解了您的要求?

If you want to find those + lines AFTER a search for ABC is found如果您想在找到 ABC 搜索后找到那些+

awk '/ABC/{f=1;print} f &&/^\+/ { print }' file

This is much simpler to understand than crafting cryptic sed expressions.这比制作神秘sed表达式更容易理解。 When ABC is found, set a flag.当找到 ABC 时,设置一个标志。 When lines starting with + is found and flag is set, print line.当找到以 + 开头的行并设置标志时,打印行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM