[英]Awk - Count Each Unique Value and Match Values Between Two Files
我有两个文件。 首先,我试图获取第 4 列中每个唯一字段的计数。
然后匹配第二个文件第二列的唯一字段值。
File1 - 第 4 列的每个唯一值和 File2 - 第 2 列包含我需要在两个文件之间匹配的值
所以本质上,我试图 -> 从 File1 的第 4 列中获取每个唯一值和值计数,如果在 file2 的 column2 中有匹配项
文件 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"
需要 output
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 "Total %s 的计数:%d, %d\n".gensub(/^([^ ]+),*/,"\1","1",b[i]),i,a[i]} }' 文件 1 文件 2
我相信我应该能够用 awk 做到这一点,但由于某种原因,我真的在努力解决这个问题。
谢谢
是的,这可以做到——这里有点冗长的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]
}
}
$ 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.