gpt4 book ai didi

bash - 使用 bash 或 DOS 在两个列表之间查找不匹配的项目

转载 作者:行者123 更新时间:2023-12-02 08:46:40 26 4
gpt4 key购买 nike

我有两个包含两个单列列表的文件:

//file1 - 唯一值的完整列表
AAA
BBB
认证中心

//文件2
AAA
AAA
BBB
BBB

//所以这里的结果是:
认证中心

我需要从 file1 生成一个值列表,这些值在 file2 中没有匹配项。我必须使用 bash 脚本(最好没有像 awk 这样的特殊工具)或 DOS 批处理文件。

谢谢。

最佳答案

方法一

看起来像是 grep 的 -v 标志的工作。

grep -v -F -f  listtocheck uniques

方法二

Drake Clarris 解决方案的一个变体(可以扩展到使用多个文件进行检查,grep 不能这样做,除非它们首先被合并),将是:

(
sort < file_to_check | uniq
cat reference_file reference_file
) | sort | uniq -u

通过这样做,file_to_check 中的任何单词在由括号中的子 shell 组合的输出中只会出现一次。 reference_file 中的单词将至少输出两次,并且出现在两个 文件中的单词将至少输出三次 - 一次来自第一个文件, 两次来自第二个文件的两个副本。

只需要找到一种方法来分离我们想要的词,即出现一次的词,这就是 sort | uniq -u 确实如此。

优化一

如果reference_file 包含很多 重复项,可能值得运行更重的

sort < reference_file | uniq
sort < reference_file | uniq

而不是 cat reference_file reference_file,以便获得更小的输出并减轻最终排序的权重。

优化二

如果我们使用临时文件,这会更快,因为可以高效地合并已经排序的文件(并且在对不同文件进行重复检查的情况下,我们可以一次又一次地重复使用相同的排序引用文件,而无需重新-排序);因此

sort < file_to_check  | uniq > .tmp.1
sort < reference_file | uniq > .tmp.2
# "--merge" works way faster, provided we're sure the input files are sorted
sort --merge .tmp.1 .tmp.2 .tmp.2 | uniq -u
rm -f .tmp.1 .tmp.2

优化三

最后,如果在一个文件中运行很长时间的相同行,例如某些日志系统可能就是这种情况,那么运行 uniq 两次可能也是值得的,一次是为了摆脱运行 (ahem) 和另一个使其唯一化,因为 uniq 在线性时间内工作,而 sortlinearithmic .

uniq < file | sort | uniq > .tmp.1

关于bash - 使用 bash 或 DOS 在两个列表之间查找不匹配的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11955734/

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