gpt4 book ai didi

shell - 从多个文本文件中提取公共(public)行并显示原始行号

转载 作者:行者123 更新时间:2023-12-04 16:16:49 25 4
gpt4 key购买 nike

我想要什么?

  1. 从 n 个大文件中提取公共(public)行。
  2. 附加每个文件的原始行号。

例子:

File1.txt 有以下内容

apple
banana
cat

File2.txt 有以下内容

boy
girl
banana
apple

File3.txt 有以下内容

foo
apple
bar

输出应该是一个不同的文件

1 3 2 apple

输出中的1、3、2分别是File1.txtFile2.txtFile3.txt的原始行号,其中公共(public)行 apple exists

我试过使用 grep -nf File1.txt File2.txt File3.txt,但它返回

File2.txt:3:apple
File3.txt:2:apple

最佳答案

将每个唯一行与一个空格分隔的行号列表相关联,该列表指示它在数组中的每个文件中的位置,如果在所有三个文件中都找到该行,则在末尾将它们并排打印。

awk '{
n[$0] = n[$0] FNR OFS
c[$0]++
}
END {
for (r in c)
if (c[r] == 3)
print n[r] r
}' file1 file2 file3

如果不知道文件数量,引用Ravinder's answer ,或者只是将 END block 中的硬编码 3 更改为 ARGC-1,如此处所示。

关于shell - 从多个文本文件中提取公共(public)行并显示原始行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63595288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com