首页 > 解决方案 > Perl - 计算文件的字数

问题描述

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

我的脚本

#!/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

感谢您提供任何信息

标签: linuxperl

解决方案


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

这是基于您的示例数据的猜测,但如果您的数据是固定宽度的,您可以将其解析为字段的一种方法是使用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

推荐阅读