首页 > 解决方案 > python在日志文件中查找匹配的字符串

问题描述

我有两个正在使用的文件,一个包含用户名列表。

$cat user.txt
johnsmith
MikeSmith
$cat logfile 
root@host1 : /home/johnsmith
root@host2 : /home/johnsmith
root@host3 : /home/MikeSmith

日志logfile包含跨多个主机的不同系统配置的转储,它还包括用户的主目录(如果有的话)。

如何遍历user.txt并查找/匹配包含用户名的任何/所有行。

标签: python-3.x

解决方案


代码:

# Read User file
f = open("user.txt", "r")
names = f.read().split() # List of user names
f.close()
# Read Log file
f = open("logfile", "r") # List of log lines
log_lines = f.read().split('\n')
f.close()

for i, log in enumerate(log_lines):
    for name in names:
        if name in log:
            print(name + ' is present in line ' + str(i + 1))

输出:

johnsmith is present in line 1
johnsmith is present in line 2
MikeSmith is present in line 3

推荐阅读