简体   繁体   English

计算文件中令牌的出现次数

[英]Count number of occurrences of token in a file

I have a server access log, with timestamps of each http request, I'd like to obtain a count of the number of requests at each second. 我有一个服务器访问日志,每个http请求的时间戳,我想获得每秒请求数的计数。 Using sed , and cut -c , so far I've managed to cut the file down to just the timestamps, such as: 使用sedcut -c ,到目前为止,我已设法将文件剪切为时间戳,例如:

22-Sep-2008 20:00:21 +0000 2008年9月22日20:00:21 +0000
22-Sep-2008 20:00:22 +0000 2008年9月22日20:00:22 +0000
22-Sep-2008 20:00:22 +0000 2008年9月22日20:00:22 +0000
22-Sep-2008 20:00:22 +0000 2008年9月22日20:00:22 +0000
22-Sep-2008 20:00:24 +0000 2008年9月22日20:00:24 +0000
22-Sep-2008 20:00:24 +0000 2008年9月22日20:00:24 +0000

What I'd love to get is the number of times each unique timestamp appears in the file. 我想得到的是每个唯一时间戳在文件中出现的次数。 For example, with the above example, I'd like to get output that looks like: 例如,通过上面的示例,我想得到如下输出:

22-Sep-2008 20:00:21 +0000: 1 2008年9月22日20:00:21 +0000:1
22-Sep-2008 20:00:22 +0000: 3 2008年9月22日20:00:22 +0000:3
22-Sep-2008 20:00:24 +0000: 2 2008年9月22日20:00:24 +0000:2

I've used sort -u to filter the list of timestamps down to a list of unique tokens, hoping that I could use grep like 我已经使用sort -u将时间戳列表过滤到一个唯一的令牌列表,希望我可以使用grep之类的

grep -c -f <file containing patterns> <file>

but this just produces a single line of a grand total of matching lines. 但这只会产生一条总共匹配线的单行。

I know this can be done in a single line, stringing a few utilities together ... but I can't think of which. 我知道这可以在一行中完成,将一些实用程序串在一起......但我想不出哪个。 Anyone know? 谁知道?

I think you're looking for 我想你在找

uniq --count

-c, --count prefix lines by the number of occurrences -c, - count前缀行数出现次数

将AWK与关联数组一起使用可能是另类解决方案。

以防万一您希望以最初指定的格式输出(最后出现的数量):

uniq -c logfile | sed 's/\([0-9]+\)\(.*\)/\2: \1/'

Using awk : 使用awk

cat file.txt | awk '{count[$1 " " $2]++;} \
                    END {for(w in count){print w ": " count[w]};}'

Tom's solution: 汤姆的解决方案:

awk '{count[$1 " " $2]++;} END {for(w in count){print w ": " count[w]};}' file.txt

works more generally. 更普遍的工作。

My file was not sorted : 我的文件没有排序:

name1 
name2 
name3 
name2 
name2 
name3 
name1

Therefore the occurrences weren't following each other, and uniq does not work as it gives : 因此,事件并没有相互跟随,并且uniq无法正常工作:

1 name1 
1 name2 
1 name3 
2 name2 
1 name3 
1 name1

With the awk script however: 但是使用awk脚本:

name1:2 
name2:3 
name3:2

maybe use xargs? 也许用xargs? Can't put it all together in my head on the spot here, but use xargs on your sort -u so that for each unique second you can grep the original file and do a wc -l to get the number. 不能把它全部放在我的头上,但是在你的排序-u上使用xargs,这样每个唯一的第二个你可以grep原始文件并做一个wc -l来获取数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM