使用正则表达式的地址范围

时间:2013-10-30 12:50:23

标签: sed

我有以下文件:

$ cat file
> First line
> Second line
> Third line
> Fourth and last line
> First line
> Second line
> Third line
> Fourth and last line

我想打印前3行,简单:

$ sed -n '1,3p' file
> First line
> Second line
> Third line

现在我想从事件First打印到事件Third

$ sed -n '/First/,/Third/p' file
> First line
> Second line
> Third line
> First line
> Second line
> Third line

啊!不完全是我想要的,我只希望第一次出现匹配的模式范围。当我将正则表达式作为我的地址时,我怎么能这样做?

4 个答案:

答案 0 :(得分:3)

将结束模式附加为退出条件:

sed -n '/First/,/Third/p; /Third/q' file

输出:

> First line
> Second line
> Third line

答案 1 :(得分:2)

您可以使用awk

执行此操作
awk '!f; /Third/ {f=1}' file
> First line
> Second line
> Third line

甚至更短更好,因为它在找到后停止处理文件。

awk '1; /Third/ {exit}' file

或者是否需要从first转到third

awk '/First/ {f=1} f; /Third/ {exit}' file

答案 2 :(得分:2)

您可以试试sed

sed -n '/First/{:loop; $!N; /Third/{p;q}; b loop;}' file

答案 3 :(得分:2)

我相信awk可以帮助你做到这一点

  awk '/First/{found=1} found{print; if(/Third/) exit}' file