如何在多行linux上进行精确匹配

时间:2016-11-02 08:56:51

标签: linux bash awk sed grep

我想只打印界面Gigabitehternet有描述的行。我用过:

cat filter.txt | awk '/interface/ || /description/'

因此,作为 filter.txt 的输出,我希望看到以下内容。

interface GigabitEthernet0/26  
description test1  

interface GigabitEthernet0/27  
description test2  

interface GigabitEthernet0/28   
description test3  


interface GigabitEthernet0/29   
description test 4 


tst:~$ cat filter.txt
interface Port-channel1   
interface FastEthernet0   
interface GigabitEthernet0/1    
interface GigabitEthernet0/2   
interface GigabitEthernet0/3   
interface GigabitEthernet0/4   
interface GigabitEthernet0/5   
interface GigabitEthernet0/6   
interface GigabitEthernet0/7   
interface GigabitEthernet0/8   
interface GigabitEthernet0/9   
interface GigabitEthernet0/10   
interface GigabitEthernet0/11   
interface GigabitEthernet0/12   
interface GigabitEthernet0/13   
interface GigabitEthernet0/14   
interface GigabitEthernet0/15  
interface GigabitEthernet0/16   
interface GigabitEthernet0/17   
interface GigabitEthernet0/18   
 description test1    
interface GigabitEthernet0/19   
 description test2    
interface GigabitEthernet0/20    
interface GigabitEthernet0/21    
interface GigabitEthernet0/22    
interface GigabitEthernet0/23    
interface GigabitEthernet0/24   
interface GigabitEthernet0/25   
interface GigabitEthernet0/26   
 description test3   
interface GigabitEthernet0/27   
 description test4   
interface GigabitEthernet0/28   
 description test5    
interface GigabitEthernet0/29   
 description test6   
interface GigabitEthernet0/30   

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

#use sed
sed -n '/interface/h;/description/{s/^ //;H;x;p}' file.txt 
#use awk
awk '/interface/{s=$0;}/description/{$1=$1;print s RS $0 ;s="";}' file.txt 
#output:
interface GigabitEthernet0/18   
description test1    
interface GigabitEthernet0/19   
description test2    
interface GigabitEthernet0/26   
description test3   
interface GigabitEthernet0/27   
description test4   
interface GigabitEthernet0/28   
description test5    
interface GigabitEthernet0/29   
description test6