去重计数的各种方法


方法一(awk):
awk '{dict[$1]++} END{for (item in dict) print dict[item]"\t"item}' /path/to/access.log | sort -nr >ip_with_counts.txt

&

array1=$(cat "$file" | awk '{type[$2]+=$3} END {for (i in type) print i, type[i]}')
array2=$(cat "$file" | awk '{type["all"]+=$3; type[$2]+=$3} END {for (i in type) print i, type[i]}')

设置一个数组,但是用不同的数组下标进行区分(比如这里的:all 和 $2 ,只是下标不同,但用的同一个数组),最后用个END进行打印即可。

=

方法二(PHP):
<?php
$all = file("email.txt");
$lines = array();
for($i=0; $i<count($all); $i++) {
    $all[$i] = trim($all[$i]);
    if($all[$i]) {
        $lines[$all[$i]] = $i; #思想:用Email地址来作为数组下标,行数为对应的数组元素的值
    }
}

// $temp = array_keys($lines);
// natsort($temp);	#自然排序
// print_r($temp);

=

方法三(Python):
f = open('email.txt', 'r')
dic = {}
i = 1
while True:
	line = f.readline().strip()
	if len(line) != 0:
		dic[line] = i
		i + =1
f.close()

print(dic['[email protected]']) #打印出需要查找的Email地址的位置(从1开始计算)
,

《“去重计数的各种方法”》 有 6 条评论

  1. 如果只需要去重,不需要统计出现次数/数量的话,可以用简化的awk版本:
    `
    awk ‘!a[$1]++’ filename.txt
    `

  2. 对一道面试题的思考
    https://mp.weixin.qq.com/s/yYwBcTd-Z4i-QkyA7v5dGg
    `
    假设我们有一个数据中心,大约1000-5000台机器,我们要对这批机器的cpu进行采样,大概5秒一次,那么这些采样数据你觉得会是一个什么样规模的数据。对于这样规模的数据,如何有效的传输,存储,检索。

    这道题目看似很简单其实考察的非常全面里面涉及到简单的编码理论、数据压缩、网络协议、分布式系统、海量数据存储和检索。
    海量数据的特点是“基数”大,随着“数量”和“时间”的增长而疯狂的增长。
    ……
    `

  3. awk中如何将某几列拼接起来?
    awk – concatenate two string variable and assign to a third
    https://stackoverflow.com/questions/27028928/awk-concatenate-two-string-variable-and-assign-to-a-third
    `
    awk ‘{b=$1$2; print b}’ file
    awk ‘{b=$1″ “$2; print b}’ file
    awk ‘{b=$1 FS $2; print b}’ file

    # 直接写在一起或是用逗号隔开都可以
    head input.txt | awk ‘NR>1 {dict[$1$2]++} END{for (item in dict) print dict[item]”\t”item}’
    head input.txt | awk ‘NR>1 {dict[$1,$2]++} END{for (item in dict) print dict[item]”\t”item}’
    `

回复 a-z 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注