Awk 跨包含单列值的多个文件查找公共值

Awk 跨包含单列值的多个文件查找公共值,awk,text-processing,comm,Awk,Text Processing,Comm,我有100个文本文件,每个文件包含一列。这些文件如下所示: file1.txt 10032 19873 18326 file2.txt 10032 19873 11254 file3.txt 15478 10032 11254 等等。 每个文件的大小不同。 请告诉我如何找到这100个文件中常见的数字 包含单个列的文件 您可以使用shell对这些文件进行排序和比较: for f in file*.txt; do sort $f|uniq; done|sort|uniq -c -d 最后一个

我有100个文本文件,每个文件包含一列。这些文件如下所示:

file1.txt
10032
19873
18326

file2.txt
10032
19873
11254

file3.txt
15478
10032
11254
等等。 每个文件的大小不同。 请告诉我如何找到这100个文件中常见的数字


包含单个列的文件

您可以使用shell对这些文件进行排序和比较:

for f in file*.txt; do sort $f|uniq; done|sort|uniq -c -d

最后一个
-c
是不必要的,只有当你想计算发生的次数时才需要它。

awk
去救援

在所有文件中查找公共元素(假定同一文件中的唯一性)


对所有出现的次数进行计数,并打印计数等于文件数的值。

无论同一数字是否可以在一个文件中多次出现,此操作都有效:

$ awk '{a[$0][ARGIND]} END{for (i in a) if (length(a[i])==ARGIND) print i}' file[123]
10032
以上使用GNU awk实现真正的多维数组和ARGID。如有必要,可对其他AWK进行简单调整,例如:

$ awk '!seen[$0,FILENAME]++{a[$0]++} END{for (i in a) if (a[i]==ARGC-1) print i}' file[123]
10032
如果每个文件中的数字都是唯一的,那么您只需要:

$ awk '(++c[$0])==(ARGC-1)' file*
10032

一个使用Bash和
comm
,因为我需要知道它是否有效。我的测试文件是
1
2
3
,因此f的

f=$(shuf -n1 -e ?)                     # pick one file randomly for initial comms file

sort "$f" > comms 

for f in ?                             # this time for all files
do 
  comm -1 -2 <(sort "$f") comms > tmp  # comms should be in sorted order always
  # grep -Fxf "$f" comms > tmp         # another solution, thanks @Sundeep
  mv tmp comms
done
f=$(shuf-n1-e?)#随机选择一个文件作为初始通信文件
对“$f”>命令进行排序
对于f in?#这是所有文件的时间
做
通信-1-2 tmp#通信应始终按顺序排序
#grep-Fxf“$f”comms>tmp#另一个解决方案,谢谢@Sundeep
中压tmp通信
完成

谢谢。这非常有帮助。
sort*| uniq-c-d
似乎可以处理这些(数量)数据。否。如果您有多个字符串出现的文件,它将不起作用。@A.N.您是对的,我没有注意到操作中没有删除限制,就在Ed回答的评论中。相同的数字在1个文件中只出现一次好的,我提供的解决方案显然也适用于这种情况,但我为这种情况添加了琐碎的解决方案。非常简洁的“琐碎的解决方案”。我不得不停下来想一想。我建议使用
grep-Fxf file1 file2
而不是
comm+sort
,关于如何选择一个文件作为初始
comm
?比我的
更适合。。。中断
:D?我尝试过类似的解决方案,但没有发布。。。不要忘记引用
“$f”
。。。来挑选,将有助于了解文件名和使用bash extglob
grep-Fxf file1.txt file2.txt>f1
,然后在中为f设置
!(文件[12]).txt
我注意到您没有,这里提供的解决方案是否都不适合您?
f=$(shuf -n1 -e ?)                     # pick one file randomly for initial comms file

sort "$f" > comms 

for f in ?                             # this time for all files
do 
  comm -1 -2 <(sort "$f") comms > tmp  # comms should be in sorted order always
  # grep -Fxf "$f" comms > tmp         # another solution, thanks @Sundeep
  mv tmp comms
done