algorithm - 在两个给定的输入文件中搜索公共(public)字符串

标签 algorithm bash shell awk

我有两个大小为 20Gb 的文件。我必须在其中搜索公共(public)字符串。假设字符串的最大长度为 20 字节。所以为了解决这个问题,我使用了以下算法,我使用的是具有四核 i3 CPU 的 8GB RAM 系统。

sort the files using any suitable sorting utility
open files A and B for reading
read wordA from A
read wordB from B
while (A not EOF and B not EOF)
{
    if (wordA < wordB)
        read wordA from A
    else if (wordA > wordB)
        read wordB from B
    else
        /* match found, store it into some other files */
        write wordA into output
        read wordA from A
}

当我在 6Gb RAM 和 120GB 可用磁盘空间以及 6 核 i3 处理器的系统中运行此算法时,上述系统配置成功运行......我的系统多次关闭。为什么会这样?

请告诉我任何其他解决此问题的方法!我们可以提高它的性能吗?

最佳答案

是的,您可以使用非常短的 awk 1-liner 显着提高性能

awk 'FNR==NR{a[$0]++;next}a[$0]' file1 file2

使用 awk,您可以找到唯一的行,而无需先对它们进行排序。你并没有真正说出你想用公共(public)线做什么,所以我只是假设你想把它们打印出来。

如果你只想打印出一个公共(public)行一次,不管它重复多少次你可以使用这个:

awk 'FNR==NR{a[$0]=1;next}a[$0]-- > 0' file1 file2

关于algorithm - 在两个给定的输入文件中搜索公共(public)字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9074203/

相关文章:

algorithm - 第一个观察在后向算法中的作用

string - 使用字典查找可能是原始字符串的所有可能单词的列表

linux - 递归编辑特定名称的文件

bash - 遍历数组,防止通配符扩展 (*)

bash - 我如何检查 ubuntu 上是否安装了 gnupg,如果没有安装,如何运行 shell 脚本来安装它?

android - sed问题:“错误模式”

CS50学分任务回顾

algorithm - 算法设计问题矩形覆盖不同的小矩形或正方形

linux - 基于shell中正则表达式的颜色突出显示输出

Linux shell 脚本 "read"命令