我生成的日志文件中包含大量信息。他们开始在服务器上占用大量空间。现在这些日志是必要的,但很多信息都不是!有人可以帮我写一个python脚本,删除文件夹中所有日志文件中包含“[TRACE]”的所有行。谢谢!
答案 0 :(得分:0)
一个非常简单的解决方案(假设您可以将完整的日志文件加载到内存中)就是这个单行程序,可以直接在python解释器中执行:
open('trimmed.log', 'w+').writelines([l for l in open('original.log').readlines() if '[TRACE]' not in l])
您必须手动更改输入文件的名称(' original.log')以及最终输出文件(' trimmed.log')。
更进一步的是这样的函数(这样你就可以在所有文件的循环中调用它):
def filter_logs(log_path, target_string='[TRACE]'):
with open(log_path) as infile:
with open(log_path + '.notrace.log', 'w+') as ofile:
for log_line in infile.readlines():
if target_string not in log_line:
ofile.write(log_line)
文件处理程序正在被明确处理(因此两个"使用"语句)并且如前所述,它允许您将路径传递到日志文件甚至更改要比较的字符串如果要删除包含其他字符串的行。它会在原始日志旁边写一个文件,但后缀为' .notrace.log' (确保你有写作权限。)
快乐修剪!
答案 1 :(得分:0)
在我看来,使用Python来完成这样的任务是个过分的
解决方案(Linux)
sed '/[TRACE]/d' filename.txt | tee filename.txt
结果
[~]% cat filename.txt
[TRACE] not needed
needed
needed2
not needed again [TRACE]
[~]% sed '/[TRACE]/d' filename.txt | tee filename.txt
[~]% cat filename.txt
needed
needed2
你可以按计划运行它,它可以超级快速地运行