【问题标题】:Parse Windows log files to pull out usernames and tally pages printed in Perl解析 Windows 日志文件以提取在 Perl 中打印的用户名和计数页面
【发布时间】:2013-06-23 00:02:30
【问题描述】:

我正在尝试用 Perl 编写日志解析器。我想输出所有用户打印页数的列表。

日志导出为制表符分隔的文本文件。有几列信息,但所有重要的信息都在最后一列。重要的部分如下所示:

Document 34, Microsoft Word - Q5_Springc_2013 owned by USERNAME on COMPUTERHOSTNAME was printed on PRINTER through port PORT. Size in bytes: 42096. Pages printed: 4. No user action is required.

#!/usr/bin/perl
use warnings;
#use strict;

print "Export the \"Printed to...\" logs from Event Viewer for the desired printer as a .txt and place it in the same directory as this script!\n";
print "Enter the text file name: ";
my $infile = <STDIN>;

if ($infile eq "\n"){
    print "No filename entered! Exiting!";
    exit 0;
}
chomp $infile;

print "Reading from file $infile\n";
open INFILE, "<$infile" or die "File does not exist!";

my %report;
while(<INFILE>){

if (/ by (\S+) on .* printed: (\d+)/s) {
    $report{$1} += $2;
}

}

print "$_ $report{$_}\n" for (keys %report);
close INFILE or die $!;

我试图从用户名数组中提取唯一的名字并计算打印,但我没有找到比这更多的父亲。如果键存在但没有任何运气,我尝试改用哈希并通过将下一个值添加到旧值来使用键/值方案。谁能帮我弄清楚从这里去哪里?

我忘了说,我想要的输出是这样的:

USER  45  
USER2 12  
USER3 120  

【问题讨论】:

  • 我相信答案是:是的,可能。
  • 编辑了代码以删除查找和连接输入文件路径的命令。正如@TLP 指出的那样,它们是不必要的。
  • 你不应该在问题中修复你的代码,这会让问题和答案看起来有点傻。

标签: regex perl parsing scripting


【解决方案1】:

这里有一个快速计算每个用户总和的方法:

my %hash;
while (<>) {
    if (/ by (\S+) on .* printed: (\d+)/s) {
        $hash{$1} += $2;
    }
}

哈希的keys是唯一的,所以它是一个用户列表。

关于相关说明:

  • 如果您正在打开一个文件,是否将当前目录名添加到文件名前并不重要。 Perl 明白,如果你想打开file.txt,它首先会在当前目录中查找。
  • $i = $i + 1 也称为 $i += 1$i++
  • 使用词法文件句柄和三个参数打开:open my $fh, "&lt;", $file or die $!
  • 假设您提供文件名作为参数,您的整个程序可以用我的 6 行代码替换。

【讨论】:

  • 谈到你的其他观点,谢谢你的提示。我已经删除了查找路径并将路径与文件名连接起来的行。使用“词法文件句柄和三参数打开”有什么好处?
  • 标记为答案。我将哈希表声明放入循环中。我把它搬走了,它现在就像一个魅力。谢谢你。我不知道哈希表会自动不允许重复键(尽管现在它很有意义),并且您可以以这种方式使用 $1$2 标量。
猜你喜欢
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
  • 2015-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多