3

我有一个充满这样行的大文件......

19:54:05 10.10.8.5 [SERVER] Response sent: www.example.com. type A by 192.168.4.5
19:55:10 10.10.8.5 [SERVER] Response sent: ns1.example.com. type A by 192.168.4.5
19:55:23 10.10.8.5 [SERVER] Response sent: ns1.example.com. type A by 192.168.4.5

我不关心任何其他数据,只关心“发送的响应”之后的内容:我想要一个域名最常见出现的排序列表。问题是我不会提前知道所有的域名,所以我不能只搜索字符串。

使用上面的示例,我希望输出符合

ns1.example.com (2)
www.example.com (1)

...其中 ( ) 中的数字是该事件的计数。

我如何/我可以在 Windows 上使用什么来执行此操作?输入文件是 .txt - 输出文件可以是任何东西。理想情况下是命令行过程,但我真的迷路了,所以我会对任何事情感到满意。

4

4 回答 4

3

猫有点出乎意料,所以让我们尝试帮助一下。这是一个 PowerShell 解决方案。如果您对它的工作方式有疑问,我鼓励您研究各个部分。

如果你的文本文件是“D:\temp\test.txt”那么你可以做这样的事情。

$results = Select-String -Path D:\temp\test.txt -Pattern "(?<=sent: ).+(?= type)" | Select -Expand Matches | Select -Expand Value
$results | Group-Object | Select-Object Name,Count | Sort-Object Count -Descending

使用您的输入,您将获得此输出

Name             Count
----             -----
ns1.example.com.     2
www.example.com.     1

由于有正则表达式,我保存了一个链接来解释它是如何工作的。

请记住,SO 当然是一个帮助程序员和编程爱好者的网站。我们将空闲时间投入到一些人获得报酬的地方。

于 2015-04-21T01:38:02.000 回答
2

你能用 PHP 做吗?

<?php
$lines = file($filename, FILE_IGNORE_NEW_LINES);

foreach($lines as $value) {
   $arr = explode(' ', $value);
   $domainarr[] = $arr[5];
}

$occurence = array_count_values($domainarr);

print_r($occurence);
?>
于 2015-04-21T01:21:42.327 回答
2

这是批量的:

@echo off
setlocal enabledelayedexpansion
if exist temp.txt del temp.txt
for /f "tokens=6" %%a in (input.txt) do (Echo %%a >> temp.txt)
for /f %%a in (temp.txt) do (
set /a count=0
set v=%%a
if "!%%a!" EQU "" (
for /f %%b in ('findstr /L "%%a" "temp.txt"') do set /a count+=1
set %%a=count
Echo !v:~0,-1! ^(!count!^)
)
)
del temp.txt

目前它将其打印到屏幕上。如果您想将其重定向到文本文件,请替换:

Echo !v:~0,-1! ^(!count!^)

和:

Echo !v:~0,-1! ^(!count!^) >> output.txt

这输出:

www.example.com (1)
ns1.example.com (2)

与样本数据

于 2015-04-21T01:40:33.560 回答
2

此批处理文件解决方案应该运行得更快:

@echo off
setlocal

rem Accumulate each occurance in its corresponding array element
for /F "tokens=6" %%a in (input.txt) do set /A "count[%%a]+=1"

rem Show the result
for /F "tokens=2,3 delims=[]=" %%a in ('set count[') do echo %%a (%%b)

输出:

ns1.example.com. (2)
www.example.com. (1)

要将结果存储在文件中,请将最后一行更改为:

(for /F "tokens=2,3 delims=[]=" %%a in ('set count[') do echo %%a (%%b^)) > output.txt
于 2015-04-21T03:19:25.870 回答