linux - 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
感谢您提供任何信息
解决方案
我将您的问题视为一个两步问题——您想解析日志文件,但您还想将该数据的元素存储到可用于计数的数据结构中。
这是基于您的示例数据的猜测,但如果您的数据是固定宽度的,您可以将其解析为字段的一种方法是使用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
推荐阅读
- python - 从朱利安字符串中获取日期和时间
- android - WebView 使用 GET 缓存进行 PUT
- python - 试图更改副本但更改原件:(
- javascript - 服务工作者“内容下载”可以比实际获取时间长吗?
- javascript - webpack:即使在断点上,也可以实时重新加载强制 chrome 重新加载
- docker - 如何使用 WLST 启用 WebLogic 摘要身份验证
- ios - iOS 无法将图像上传到移动数据/4G 网络上的服务器,而在 Wifi 中它工作正常
- python - 我对 Python 的 for in 循环有疑问
- android - 从 App Widget 管理点击按钮
- python - text3D 上升或下降与相同的 zdir matplotlib python 绘图图