2015-01-07 71 views
-1

我想查找两个单词之间出现的文本,而这两个单词不在同一行,两者都出现在不同的行上,所以我想查找介于两行之间的行(文本行)也就是说如何获取文本文件中两个单词之间的文本行?

例如:

This is an example 
first 

second 
third 
vs. 

fourth 

所以我想找到first和“与”之间的文本话。
我该如何使用sed命令来获取?

回答

0

您可以使用范围模式:打印

~$ sed -n '/first/,/vs/p' f 
first 

second 
third 
vs. 

一切和vs之间firstp),其他一切都是不-n

如果你不希望的模式:

~$ sed -n ' 
    /first/,/vs./ { 
     /first/n 
     /vs/ !p 
    } 
' f 

second 
third 

/first/n跳过那些具有第一线,和一切不符合vs,打印(!p
或者

~$ sed -n ' 
    /first/,/vs./ { 
     /first/n 
     /vs/n 
     p 
    } 
' f 

second 
third 

如果匹配则跳过firstvs,否则打印。


匹配vs后的第一个 “选择” 之后结束,你就必须退出(q):

~$ sed -n '/first/,/vs/p;/vs/q' f f 

~$ sed -n ' 
    /first/,/vs./ { 
     /first/n 
     /vs/q 
     p 
    } 
' f f 
1
sed -n '/first/ { :loop; n; /vs/q; p; b loop }' filename 

即:

/first/ { # when you encounter a line that matches /first/ (contains it) 
    :loop  # in a loop: 
    n   # fetch the next line 
    /vs/q  # if it contains "vs", quit 
    p   # otherwise print it 
    b loop  # and loop. 
} 

优点是不需要指定两次模式。要包含模式范围边界,使用

sed -n '/first/ { p; :loop; n; p; /vs/q; b loop }' filename 

顺便说一句,如果你不是想只是第一场比赛,也将是一个极好的技巧摆脱起始和结束的模式范围的线不重复你自己,这是

sed -n '/first/,/vs/ { //!p }' filename 

诀窍是,//重复上次尝试匹配。在这种情况下,这是上次尝试的模式范围边界 - /first/第一次和/vs/此后。 //!p的意思是“如果最后尝试的比赛没有成功,则打印”。在这种情况下,转换为:“如果此行不是图案范围边框,请将其打印出来。”

+0

如何使用上述正则表达式不区分大小写? –

+0

是的。分别使用'/ first/I'和'/ vs/I q'来代替'/ first /'和'/ vs/q'。 – Wintermute

+0

感谢您的帮助:) –

相关问题