python-3.x - python在日志文件中查找匹配的字符串
问题描述
我有两个正在使用的文件,一个包含用户名列表。
$cat user.txt
johnsmith
MikeSmith
$cat logfile
root@host1 : /home/johnsmith
root@host2 : /home/johnsmith
root@host3 : /home/MikeSmith
日志logfile包含跨多个主机的不同系统配置的转储,它还包括用户的主目录(如果有的话)。
如何遍历user.txt并查找/匹配包含用户名的任何/所有行。
解决方案
代码:
# 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
推荐阅读
- python - 如何在按下和释放鼠标时存储鼠标位置?
- mediawiki - AD 组授权 - 用户未授权
- powerbi - Power BI - 计算客户运行逾期余额
- javascript - React native - 使用 android studio 编译包
- c++ - OpenCL 内核计时测量 0 秒或导致 SIGABRT
- google-apps-script - Google Script,for循环在达到其条件之前停止,导致它无法继续通过未检查的数据
- javascript - useEffect 缺少依赖项,但是当我添加它时,出现“超出最大更新深度”错误
- github - 如何使用 Jekyll 在 Github 页面中使用 font awesome
- python - 打字!带有 pyautogui 的字符
- java - Scrollbar in Javafx in not scrolling