【问题标题】:Awk - Count Each Unique Value and Match Values Between Two Filesawk - 计算两个文件之间的每个唯一值并匹配值
【发布时间】:2020-12-27 19:32:57
【问题描述】:

我有两个文件。首先,我试图获取第 4 列中每个唯一字段的计数。

然后匹配第二个文件第二列的唯一字段值。

File1 - 第 4 列的每个唯一值和 File2 - 第 2 列包含我需要在两个文件之间匹配的值

所以本质上,我正在尝试 -> 如果 file2 的 column2 中有匹配项,则从 File1 的第 4 列中获取每个唯一值和值计数

文件1

1 2 3 6 5 

2 3 4 5 1 

3 5 7 6 1

2 3 4 6 2

4 6 6 5 1

文件2

hello "6"

hi "5"

需要的输出

total count of hello,6 : 3

total count of hi,5 : 2

我的测试代码

awk 'NR==FNR{a[$4]++}NR!=FNR{gsub(/"/,"",$2);b[$2]=$0}END{for(i in b){ printf "%s,%d 的总数: %d\n",gensub(/^([^ ]+).*/,"\1","1",b[i]),i,a[ i]}}' 文件 1 文件 2

我相信我应该能够用 awk 做到这一点,但由于某种原因,我真的在努力解决这个问题。

谢谢

【问题讨论】:

  • 您应该至少包含一个案例,其中 file1 的第 4 列值没有出现在 file2 中,反之亦然,因此我们可以测试潜在的解决方案是否真的有效,而不仅仅是晴天案例。

标签: linux awk


【解决方案1】:

是的,这是可以做到的——这里是一个有点冗长的awk 版本(使用 GNU awk 及其不符合 POSIX 的扩展 gensub):

tink@box ~/tmp$ awk 'NR==FNR{a[$4]++}NR!=FNR{gsub(/"/,"",$2);b[$2]=$0}END{for( i in b){printf "Total count of %s,%d : %d\n",gensub(/^([^ ]+).*/,"\\1","1",b[i]),i,a[i]}}' File1 File2
Total count of hi,5 : 2
Total count of hello,6 : 3

几句解释:

NR == FNR {  # while we're on the first file, count all values in column 4
        a[$4]++
}
NR != FNR { # on the second file, strip the quotes from field two, use 2 as
            # index of the array for the second file
        gsub(/"/, "", $2)
        b[$2] = $0
}
# END rule(s)
END { # after both files were processed, pull a match for every line in the 
      # second array, and print it with the count of the occurrences in File1
        for (i in b) {
                printf "Total count of %s,%d : %d\n", gensub(/^([^ ]+).*/, "\\1", "1", b[i]), i, a[i]
        }
}

【讨论】:

    【解决方案2】:
    $ cat tst.awk
    BEGIN { FS = "[[:space:]\"]+" }
    NR==FNR {
        cnt[$4]++
        next
    }
    { printf "total count of %s,%d : %d\n", $1, $2, cnt[$2] }
    

    $ awk -f tst.awk file1 file2
    total count of hello,6 : 3
    total count of hi,5 : 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-09
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多