模式匹配时获取特定的行集

时间:2018-05-15 12:18:41

标签: bash unix

输入

abc  
cde  
efg  
xyz  
abc  
jkl  
mno  
xyz 

现在我想获得模式abc和xyz之间的界限,但是第二次匹配。

输出

cde  
efg

3 个答案:

答案 0 :(得分:1)

awk '/abc/{count++;next} count==2{flag=1}  /xyz/ && flag{print val;val=flag=""} flag{val=val?val ORS $0:$0}' Input_file

<强> 说明:

awk '
/abc/{                    ##Checking condition here if a line is having string abc in it then do following.
   count++;               ##Increment variable named count with 1 each time cursor comes here.
   next}                  ##Using next keyword which will skip all further statements written.
count==2{                 ##Checking condition here if a variable count value is 2 here then do following.
   flag=1}                ##Setting variable named flag value is set to 1 here.
/xyz/ && flag{            ##Checking conditions here is a line is having string xyz and variable named flag is SET here then do following.
   print val;             ##Printing variable named val here.
   val=flag=""}           ##Nullifying variable val and flag here.
flag{                     ##Checking condition here if variable flag value is NOT NULL then do following.
   val=val?val ORS $0:$0  ##Create variable named val and concatenate its value with its own value each time cursor comes here.
}' Input_file             ##Mentioning Input_file name here.

答案 1 :(得分:0)

Awk 方法:

awk '/abc/ && ++c == 2{ f = 1; next }/xyz/{ f = 0 }f' file

输出:

jkl
mno

答案 2 :(得分:0)

当你使用sed时,你必须做一些事情才能找到第二击 首先选择匹配的行。这样你肯定当匹配时第一行是abc(我不写^abc$,也许子串也应该匹配)。

sed -n '/abc/,/xyz/ p' inputfile 

现在删除直到第二个abc。当您的输入只有一个abc时,所有行都将被删除。

sed '/abc/,/abc/d'

当你从xyz删除行直到EOF时,这将是

sed -n '/abc/,/xyz/ p' inputfile | sed '/abc/,/abc/d; /xyz/,$ d'