从大型文件中获取大量Grep模式

特蕾莎修女和少年

我有一个文件,每天增长约200,000行,并且全部由以下三行组成:

1358726575123       # key
    Joseph Muller   # name
    carpenter       # job
9973834728345
    Andres Smith
    student
7836472098652
    Mariah Anthony
    dentist

现在,我还有另一个文件,可以从中提取大约10,000个键模式,例如1358726575123然后,我for使用这些模式运行循环,并且必须对照第一个文件检查它们。如果文件不包含这种模式,则将模式保存在第三个文件中以进行进一步处理:

for number in $(grep -o '[0-9]\{12\}' file2); do  # finds about 10.000 keys
     if ! grep -q ^$number$ file1; then           # file1 is a huge file
         printf "$number\n" >>file3               # we'll process file3 later
     fi
done

示例代码将一个巨大的文件捕获了10,000次,我整天大约每分钟运行一次此循环

由于巨大的文件不断增长,我该怎么做才能使所有这些工作更快并节省一些CPU?我想知道是否通过密钥对其进行排序(如果可以,怎么办?)还是使用db而不是纯文本排序会有所帮助...

彼得·奥

此答案基于potongawk发布答案对于主文件中相同的600万行1万个它的速度是方法(在我的系统上)的两倍...(现在已更新为使用FNR, NR)
comm

尽管awk它比当前的系统快,并且将为您和您的计算机提供一些喘息的空间,但是请注意,当数据处理如您所描述的那样密集时,通过切换到专用数据库将获得最佳的总体效果;例如。SQlite,MySQL ...


awk '{ if (/^[^0-9]/) { next }              # Skip lines which do not hold key values
       if (FNR==NR) { main[$0]=1 }          # Process keys from file "mainfile"
       else if (main[$0]==0) { keys[$0]=1 } # Process keys from file "keys"
     } END { for(key in keys) print key }' \
       "mainfile" "keys" >"keys.not-in-main"

# For 6 million lines in "mainfile" and 10 thousand keys in "keys"

# The awk  method
# time:
#   real    0m14.495s
#   user    0m14.457s
#   sys     0m0.044s

# The comm  method
# time:
#   real    0m27.976s
#   user    0m28.046s
#   sys     0m0.104s

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章