我需要一个linux日志文件,将数据输入到mysql表中,并将每个字段分隔成列。我一直在尝试使用加载数据填充命令。唯一的问题是,数据没有被分隔,并且我不能用“”终止字段,因为文件在日志消息中包含空格。如果有人知道,请告诉我
文件示例:
2011-01-17 10:18:20用户xxxxxx请求备份xxxxx(xxxxx)
2011-01-17 10:18:29停止当前满xxxxxx,由backuppc请求(backoff=)
2011-01-17 10:18:33用户xxxxxx请求备份xxxxxx(xxxxxx)
2011-01-17 10:18:51备份在xxxxxx取消(接收信号=ALRM)
2011-01-17 10:18:52在xxxxxx上启动完全备份(pid=xxxxxx,share=xxxxxx$)
2011-01-17 10:24:18在xxxxxx上启动完全备份(pid=xxxxxx,share=xxxxxx$)
2011-01-17 11:00:01下一次醒来是2011-01-17 12:00:01
2011-01-17 12:00:03下一次醒来是2011-01-17 13:00:00
2011-01-17 13:00:01下一次醒来是2011-01-17 14:00:00

最佳答案

预先格式化此文件。我假设您的文件中的空白行不存在(否则,您可以使用注释代码删除它们)。假设您正在使用python:

parsed = open("parsed.txt", 'a')
    with open("log.txt") as f:
    for i, line in enumerate(f):
        # use if your lines have spaces in between
        # if i % 2 == 0:
        parsed.write(line.replace(" ",",",2))

给你一个文件,比如:
2011-01-17,10:18:20,User xxxxxx requested backup of xxxxx (xxxxx)
2011-01-17,10:18:52,Started full backup on xxxxxx (pid=xxxxxx , share=xxxxxx$)
2011-01-17,10:24:18,Started full backup on xxxxxx (pid=xxxxxx , share=xxxxxx$)
...

现在你可以:
LOAD DATA INFILE 'parsed.txt' INTO TABLE db.my_table;

关于python - 使用Python将LOG文件信息输入MySQL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4748400/

10-15 11:43