Skip to main content
 首页 » 编程设计

python之使用 bash 或 python 从文件中提取行

2025年05月04日14jackei

这是我的文件内容,它是 pflogsumm 的输出

Host/Domain Summary: Messages Received  
--------------------------------------- 
 msg cnt   bytes   host/domain 
 -------- -------  ----------- 
    415     5416k  abc.com 
     13    19072   xyz.localdomain 
 
Senders by message count 
------------------------ 
    415   alert@example.com 
     13   root@jelly.localdomain 
 
Recipients by message count 
--------------------------- 
    506   alert@apple.com            <= Extract from here to ... 
     70   info@pafpro.org.us 
     .. 
     ... 
     19   gems@gmail.com 
     17   info@aol.com 
     13   hemdem@gmail.com           <= Extract ends here 
 
Senders by message size 
----------------------- 
   5416k  alert@google.com 
... 
 ... 

输出的信息似乎由“标题”和“换行”分隔。例如Recipients by message count ...<contents of interest> ... NewLine 我尝试使用以下 sed 表达式,但它在匹配字符串 "Recipients by message count" 后返回所有行

sed -nr '/.*Recipients by message count/,/\n/ p'

期望的输出:"Recipients by message count" 下的所有电子邮件

请您参考如下方法:

使用 awk:

awk '/Recipients by message count/{p=1}!$0{p=0}p' input_file 

将打印 Recipients by message count block

分割:

/Recipients by message count/ {p=1} # When /pattern/ is matched set p = 1 
!$0 {p=0}                           # When input line is empty set p = 0 
p                                   # Print line if p is true, short for: 
                                    # p { print $0 }