linux shell获取多文件交集

标签 linux shell

我有一些txt文件示例1.txt 2.txt 3.txt 4.txt 我想获取1.txt 2.txt 3.txt 4.txt内容交集

cat 1.txt 2.txt | sort | uniq -c > tmp.txt
cat tmp.txt 3.txt | sort | uniq -c > tmp2.txt 
and so on ....

有更好的方法吗?

input text
1.txt
1
2
3
4

2.txt
1
2
3

3.txt
1
2

4.txt
1
5

expected output:
1

最佳答案

对于显示的示例,请尝试以下 awk 代码。

第一个解决方案:这认为您可能在单个 Input_file 本身中有重复行值,那么您可以尝试以下操作:

awk '
!arr2[FILENAME,$0]++{
  arr1[$0]++
}
END{
  for(i in arr1){
    if(arr1[i]==(ARGC-1)){
       print i
    }
  }
}
' *.txt


第二个解决方案:此解决方案假设 Input_file 中没有重复项,如果是这种情况,请尝试以下操作:

awk '
{
  arr[$0]++
}
END{
  for(i in arr){
    if(arr[i]==(ARGC-1)){
       print i
    }
  }
}
' *.txt

说明:为上述内容添加详细说明。

awk '                      ##Starting awk program from here.
{
  arr[$0]++                ##Creating an array named arr with index of $0 and keep increasing its value.
}
END{                       ##Starting END block of this program from here.
  for(i in arr){           ##Traversing through array arr here.
    if(arr[i]==(ARGC-1)){  ##Checking condition if value of current item in arr is Equal to total number of files then print it.
       print i
    }
  }
}
' *.txt                    ##Passing all .txt files as an input to awk program from here.

关于linux shell获取多文件交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74181035/

相关文章:

linux - 无法再安装 Perlapi?

shell - 从 valgrind 输出中过滤掉垃圾

Bash 脚本 : Error, 文件意外结束

c++ - Cin循环永不终止

Linux命令查找目录中所有具有相同名称但不同扩展名的文件?

java - Selenium-jenkins 与 Linux。 “指定的 firefox 二进制位置不存在或不是真实文件

linux - "zip -m"目录变空不删除

Python 生成的子进程 ID

linux - 如何从 Bash 中的并行子 shell 获取结果?

linux - 将文件复制到备份目录保留文件夹结构