gpt4 book ai didi

linux - 如何使用动态 grep 模式尾随文件?

转载 作者:太空宇宙 更新时间:2023-11-04 04:44:54 32 4
gpt4 key购买 nike

我有一个日志文件,其中包含有关不同用户的行,并且我正在实时跟踪该文件。我想过滤掉仅与我指定的用户相关的行,例如:1234。日志条目如下所示:

ID:101 Username=1234
ID:102 Username=1234
ID:999 UNWANTED LINE (because this ID was not assigned to user 1234)
ID:102 some log entry regarding the same user
ID:123 UNWANTED LINE (because this ID was not assigned to user 1234)
ID:102 some other text
ID:103 Username=1234
ID:103 blablabla

动态 ID 在“ID:101 Username=1234”等行中分配给用户。以该 ID 开头的任何后续行都属于同一用户,需要显示。我需要一个动态尾部来获取与指定用户 (1234) 相关的所有 ID,并按如下方式过滤前面的行:

ID:101 Username=1234
ID:102 Username=1234
ID:102 some log entry regarding the same user
ID:102 some other text
ID:103 Username=1234
ID:103 blablabla

我需要首先过滤找到“Username=1234”的行,然后提取“ID:???”从该行开始,然后尾部包含“ID:???”的所有行。当找到另一行“Username=1234”时,提取新 ID 并使用它来显示具有该新 ID 的后续行。

当我使用 cat 时,我可以链接 grep 来过滤掉 ID,但是当我在尾部链接它们时,它不起作用。但即使我可以,我如何“观察”新的 ID 值并动态更新我的 grep 模式???

提前致谢!

最佳答案

这是 Awk 可以轻松处理的任务(也可以使用 Perl 或 Python 处理)。

awk '$2 == "Username=1234" { ids[$1]++; } $1 in ids  { print }' data

第一个模式/操作对记录 ids 数组中 $2Username=1234 的条目的 ID:xxx 值。第二个模式/操作对查看 ID:xxx 条目是否在 ids 中列出;如果是,则打印该行。 Username=1234 行满足这两个条件(至少在将条目添加到数组之后)。

How do I use it so it can act like tail (i.e. print the new lines as they're added to data)?

tail -f logfile | awk …

当然,您可能会错过命令的 awk 部分中的数据文件名称。您唯一需要注意的是 tail 不会挂起等待填充管道缓冲区。这可能不会成为问题,但如果 Awk 输入中出现行的时间比您预期的要长,您可能必须仔细查看 tail 的选项。

I realized that ID:XXX doesn't necessarily always come at position $1... is there a way to match the ID with a regular expression regardless of its position in the line ($1, $2, ...)?

是的:

awk '$2 == "Username=1234" { ids[$1]++; }
{ for (i = 1; i <= NF; i++) if ($i in ids) { print; break }' data

第二行匹配每一行,并针对该行中的每个字段检查该字段是否存在于 ids 数组中。如果是,它会打印该行并跳出循环(在这种情况下,您可以使用 next 而不是 break,尽管两者通常并不等效)。

关于linux - 如何使用动态 grep 模式尾随文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42640226/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com