【问题标题】:Merge and remove redundant lines *among* files合并和删除*文件中的冗余行
【发布时间】:2021-03-31 20:57:57
【问题描述】:

我需要合并多个文件,删除 个文件中的冗余行,同时保留 个文件中的冗余行。我的文件的示意图如下:

文件1.txt

1
2
3
3
4
5
6

文件2.txt

6
7
8
8
9

文件3.txt

9
10
10
11

期望的输出是:

1
2
3
3
4
5
6
7
8
8
9
10
10
11

我更愿意在 awk、bash 或 R 语言中获得解决方案。我在网上搜索了解决方案,虽然有很多解决方案*(请在下面找到一些示例),但无论它们位于文件内部还是外部,都会删除重复的行。

提前致谢。 阿图罗

【问题讨论】:

  • I searched the web for solutions,请您将它们添加到您的问题中(以避免近距离投票和否决),因为它强烈鼓励原始发帖人在他们的代码中添加他们的努力问题(不是我的反对票),谢谢。
  • 谢谢。我添加了一些先前解决方案的示例,这些示例从文件内部和外部文件中删除了冗余行。
  • 如果file3.txt == 9 9 10 10 12,你会期待什么?你是保留双 9's 还是同时删除 '9's 因为 file2.txt 也有一个 '9
  • @markp-fuso.Tkanks。我会保留双 9。
  • @markp-fuso 和@RavinderSingh13。感谢您的 cmets,很抱歉从一开始就不清楚。但是,我将发布一个新的更新问题。无论如何,我的要求的底线是应该删除来自不同文件的任何冗余行。

标签: r bash awk merge


【解决方案1】:

对于您显示的示例,您能否尝试以下操作。这不会删除文件中的冗余行,但会删除它们。

awk '
FNR==1{
  for(key in current){
    total[key]
  }
  delete current
}
!($0 in total)
{
  current[$0]
}
' file1.txt file2.txt  file3.txt

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

awk '                                ##Starting awk program from here.
FNR==1{                              ##Checking condition if its first line(of each file) then do following.
  for(key in current){               ##Traverse through current array here.
    total[key]                       ##placing index of current array into total(for all files) one.
  }
  delete current                     ##Deleting current array here.
}
!($0 in total)                       ##If current line is NOT present in total then do following.
{
  current[$0]                        ##Place current line into current array.
}
' file1.txt file2.txt  file3.txt     ##Mentioning Input_file names here.

【讨论】:

  • @Arturo,欢迎您,继续分享好问题,继续学习加油 :)
  • @akrun,谢谢先生鼓励你让我开心:) ?
  • 很好的答案拉文德辛格。我刚开始学习一门新语言。很有趣。
【解决方案2】:

这是使用diff 及其输出格式添加到https://stackoverflow.com/a/15385080/3358272 的技巧。此处可能假设“已排序”,未经测试。

out=$(mktemp -p .)
tmpout=$(mktemp -p .)
trap 'rm -f "${out}" "${tmpout}"' EXIT
for F in ${@} ; do
    { cat "${out}" ;
      diff --changed-group-format='%>' --unchanged-group-format='' "${out}" "${F}" ;
    } > "${tmpout}"
    mv "${tmpout}" "${out}"
done
cat "${out}"

输出:

$ ./question.sh F*
1
2
3
3
4
5
6
7
8
8
9
10
10
11

$ diff <(./question.sh F*) Output.txt

(根据markp-fuso's comment,如果File3.txt 有两个9s,这将保留两者。)

【讨论】:

  • 感谢您建议对此进行调查。我必须承认我没有考虑过这种可能性。
猜你喜欢
  • 2011-05-03
  • 2012-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-08
  • 2019-07-23
  • 1970-01-01
相关资源
最近更新 更多