我有日志文件。我想从特定行中提取电子邮件列表。示例日志文件:
05:06:48,311 INFO http-nio-8080-exec-81 controller.IndexController:221 - Attempt to login: [[email protected]]. Headers: ["content-length": "52", ...]
15:06:48,311 INFO http-nio-8080-exec-81 controller.IndexController:221 - Attempt to login: [[email protected]]. Headers: ["content-length": "52", ...]
09:40:21,187 INFO http-nio-8080-exec-31 security.AuthAuthenticationProvider:81 - User: [16167]. Wrong code. Telegram: [0]. Google: [0]
我的脚本:
cat file.log | sed -r 's/.*Attempt to login: \[(.*)\]\..*/\1/' | sort | uniq > file.log.filtered.txt
我得到file.log.filtered.txt:
09:40:21,187 INFO http-nio-8080-exec-31 security.AuthAuthenticationProvider:81 - User: [16167]. Wrong code. Telegram: [0]. Google: [0]
[email protected]
为什么过滤文件中有一行“AuthAuthenticationProvider”?
答案1
sed
因为您仅在包含 : 的行上运行命令Attempt to login
,所以其他行将保持不变。
您可以像这样更改您的代码:
grep 'Attempt' file.log | sed -r 's/.*Attempt to login: \[(.*)\]\..*/\1/' | sort | uniq > file.log.filtered.txt
所以它首先排除其他行,然后提取电子邮件地址。
或者这个:
sed -re 's/.*Attempt to login: \[(.*@.*)\]\..*/\1/;t;d' file.log | sort | uniq
或者甚至是这个:
sed -nr 's/.*Attempt to login: \[(.*@.*)\]\..*/\1/p' file.log | sort | uniq
或者直接使用 grep:
grep 'Attempt' file.log | grep -o '[[:alnum:]+\.\_\-]*@[[:alnum:]+\.\_\-]*' | sort | uniq
最后一个命令形式的正则表达式这里