我想计算文件中的单词数,并希望得到相同单词数的结果

我的剧本

#!/usr/bin/perl

#use strict;
#use warnings;

use POSIX qw(strftime);
$datestring = strftime "%Y-%m-%d", localtime;

print $datestring;

my @files = <'/mnt/SESSIONS$datestring*'>;
my $latest;

foreach my $file (@files) {
  $latest = $file if $file gt $latest;
}

@temp_arr=split('/',$latest);

open(FILE,"<$latest");
print "file loaded \n";
my @lines=<FILE>;
close(FILE);

#my @temp_line;

foreach my $line(@lines) {

    @line=split(' ',$line);
    #push(@temp_arr);

    $line =~ s/\bNT AUTHORITY\\SYSTEM\b/NT__AUTHORITY\\SYSTEM/ig;

    print $line;

    #print "$line[0] $line[1] $line[2] $line[3] $line[4] $line[5] \n";

}


我的日志文件

SID        USER                      TERMINAL        PROGRAM
---------- ------------------------- --------------- -------------------------
         1 SYSTEM                    titi            toto (fifi)
         2 SYSTEM                    titi            toto (fofo)
         4 SYSTEM                    titi            toto (bobo)
         5 NT_AUTHORITY\SYSTEM       titi            roro
         6 NT_AUTHORITY\SYSTEM       titi            gaga
         7 SYSTEM                    titi            gogo (fifi)

         5 rows selected.


我想要结果:

User = 3 SYSTEM with program toto
, User = 1 SYSTEM with program gogo


感谢您提供任何信息

最佳答案

我认为您的问题分为两个步骤-您想解析日志文件,但是您还想将该数据的元素存储到可用于计数的数据结构中。

这是基于样本数据的猜测,但是如果您的数据是固定宽度的,则可以将其解析为字段的一种方法是使用unpack。我认为substr可能会更有效,因此请考虑需要解析多少个文件以及每个文件有多长时间。

我会将数据存储到一个哈希中,然后在读取所有文件之后取消引用它。

my %counts;

open my $IN, '<', 'logfile.txt' or die;
while (<$IN>) {
  next if length ($_) < 51;
  my ($sid, $user, $terminal, $program) = unpack 'A9 @11 A25 @37 A15 @53 A25', $_;

  next if $sid eq '---------';  # you need some way to filter out bogus or header rows

  $program =~ s/\(.+//;         # based on your example, turn toto (fifi) into toto

  $counts{$user}{$program}++;
}
close $IN;

while (my ($user, $ref) = each %counts) {
  while (my ($program, $count) = each %$ref) {
    print "User = $count $user with program $program\n";
  }
}


程序输出:

User = 3 SYSTEM with program toto
User = 1 SYSTEM with program gogo
User = 1 NT_AUTHORITY\SYSTEM with program roro
User = 1 NT_AUTHORITY\SYSTEM with program gaga

关于linux - Perl-计算文件字数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53929955/

10-14 17:23
查看更多