Skip to main content
 首页 » 编程设计

python之数字的正则表达式匹配并将它们重定向到不同的输出文件

2025年05月04日35findumars

这是我当前的日志文件

event_1.log

a   0   3.2 1024    1   0   0 
a   0   6.4 2048    2   0   0 
le  0   9.6 2048    2   0   0 
a   0   12.8    2048    2   0   0 
le  0   12.8    2048    2   0   0 
ll  0   19.6    2048    2   0   0 
a   1   19.6    1024    1   0   0 
a   1   22.4    3072    3   0   0 
d   0   19.2    2048    2   0   0 
le  1   22.4    2048    2   0   0 
ll  1   22.8    2048    2   0   0 
d   1   22.8    1024    1   0   0 
a   0   26  2048    2   0   0 

基于第二列,我需要创建文件名 {second_column}.log。我只需要提取具有 first_column 等于 a 或 d。应跳过其他(le ​​和 ll)。

以下是我的预期输出

0.log

a   0   3.2 1024    1   0   0 
a   0   6.4 2048    2   0   0 
a   0   12.8    2048    2   0   0 
d   0   19.2    2048    2   0   0 
a   0   26  2048    2   0   0 

1.log

a   1   19.6    1024    1   0   0 
a   1   22.4    3072    3   0   0 
d   1   22.8    1024    1   0   0 

这是我尝试过的方法,但我显然是正则表达式的新手。我对其他解决方案(shell、sed、awk 等)持开放态度。

import re 
 
input_file = open("event_1.log", "r") 
output_file = open("column2.log", "w") # want this to be the name of the 2nd column   
for line in input_file: 
    match_defines = re.match(r'\s*([a-z]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)', line) 
 
    if match_defines.group(1) == 'a': 
        newline1= "\ndef %s():\n    return %s" % (match_defines.group(1),match_defines.group(2)) 
        output_file.write(newline1) 
 
    else: 
        output_file.write(line) 

非常感谢任何帮助。谢谢

请您参考如下方法:

cat event_1.log | grep "^[a|d]" | while read l; do i=`echo $l |awk '{print $2}'`; echo $l >> ${i}.log; done