[英]Count the most common occurrences of a unknown strings in a file
我有一個很大的文件,像這樣......
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 - 輸出文件可以是任何內容。 理想情況下是一個命令行程序,但我真的迷失了所以我會對任何事情感到滿意。
貓有點不合適所以讓我們嘗試一點幫助。 這是一個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當然是一個幫助程序員和編程愛好者的網站。 我們正在投入我們的空閑時間,因為有些人得到了報酬。
你能用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);
?>
這是批量的:
@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)
隨着樣本數據
此Batch文件解決方案應該運行得更快:
@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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.