[英]How do I extract information from a text file after a certain word in python or linux?
我正在用python编写回归脚本,以验证我们的库通过了所有单元测试。 我正在将所有输出写入需要以这种格式命名的.txt
文件: reg_results_yyyy_mm_dd_hh_mm_ss_rrrrrr_ssssss.txt
,其中yyyy_mm_dd_hh_mm_ss
是年,月,日,小时,分钟和秒修订, rrrrrr
数我们的库和ssssss
的“通过”或“失败”。
在日志文件中,它将指出“已签出修订版129”,其中129是要更改的数字。 我需要提取“修订”之后的任何数字。 在日志文件的末尾,它将显示“通过的单元测试”或“失败的单元测试”,我需要提取通过/失败的信息。
我想知道如何搜索日志文件并从中提取修订号和通过/失败,以便适当地重命名日志文件。
我已经研究了grep linux命令,但是不确定如何仅获取特定信息。
您可以将正则表达式与grep(来自Bash)一起使用,或者因为标记了此Python,所以可以使用:
import re
with open('/tmp/tgt.txt') as f:
for line in f:
m=re.match(r'Checked out revision (\d+)\s+(\w+)', line)
if m:
print m.group(1), m.group(2)
给定这样的文件:
blah
blew blah
blah de blah
Checked out revision 129 PASSED Unit Test
blah
blew blah
Checked out revision 135 FAILED Unit Test
blah de blah
印刷品:
129 PASSED
135 FAILED
使用正则表达式:
import re
rev = None
pass_or_fail = None
with open(path_to_your_log_file, 'r') as f:
for line in f:
if rev is None:
found_rev = re.findall(r'Checked out revision (\d+)', line):
if found_rev:
rev = int(found_rev[0])
continue
if pass_or_fail is None:
found_pass_fail = re.findall(r'(PASSED|FAILED) Unit Tests', line):
if found_pass_fail:
pass_or_fail = found_pass_fail[0]
if pass_or_fail is not None and rev is not None:
break
这可以用sed
完成。 如果一切都在一行上(如另一答案中所建议),则非常简单:
sed -n 's/^Checked out revision \([0-9]\+\) \(FAILED\|PASSED\) Unit Tests$/\1 \2/p'
如果您感兴趣的两个位在不同的行上,这会有点困难,但是如果您认识到一个或两个sed
成语,就很容易了:
sed -n '/^Checked out revision \([0-9]\+\)/{s//\1/;h}; /^\(FAILED\|PASSED\) Unit Tests$/{s//\1/;H;g;s/\n/ /p}'
这有一点解释:
sed -n '/^Checked out revision \([0-9]\+\)$/{ # Match revision, capture number
s//\1/ # Make matched group (number) the only thing in pattern space
h # Save the pattern space (number) to hold space
}
/^\(FAILED\|PASSED\) Unit Tests$/{ # Match pass/fail line, capturing pass/fail
s//\1/ # Make pass/fail the only thing in pattern space
H # Append pattern space to hold space with newline
g # Fetch hold space to pattern space
s/\n/ / # Replace newline with space
p # Print out pattern space
}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.