繁体   English   中英

用于合并具有匹配第一个字段的行的命令行,50 GB 输入

[英]Command line to merge lines with matching first field, 50 GB input

不久前,我问了一个关于合并具有共同第一个字段的行的问题。 这是原始的: 命令行匹配具有匹配第一个字段(sed、awk 等)的行

样本输入:

a|lorem
b|ipsum
b|dolor
c|sit
d|amet
d|consectetur
e|adipisicing
e|elit

期望的输出:

b|ipsum|dolor
d|amet|consectetur
e|adipisicing|elit

这个想法是,如果第一个字段匹配,则合并行。 输入已排序。 实际内容更复杂,但使用管道作为唯一分隔符。

上一个问题中提供的方法在我的 0.5GB 文件上运行良好,处理时间约为 16 秒。 但是,我的新文件大约大 100 倍,我更喜欢流式传输的方法。 理论上,这将能够在大约 30 分钟内运行。 先前的方法在运行 24 小时后未能完成。

在 MacOS(即 BSD 类型的 unix)上运行。

想法? [注意,先前问题的先前答案不是单行的。]

您可以将结果即时附加到文件中,这样您就不需要构建 50GB 的数组(我假设您没有内存!)。 此命令将连接字符串中每个不同索引的连接字段,该字符串被写入以相应索引命名的文件中,并带有一些后缀。

编辑:根据 OP 的评论,内容可能有空格,我建议使用-F"|" 而不是sub并且以下答案旨在写入标准输出

(新)代码:

# split the file on the pipe using -F
# if index "i" is still $1 (and i exists) concatenate the string
# if index "i" is not $1 or doesn't exist yet, print current a
# (will be a single blank line for first line)
# afterwards, this will print the concatenated data for the last index
# reset a for the new index and take the first data set
# set i to $1 each time
# END statement to print the single last string "a"
awk -F"|" '$1==i{a=a"|"$2}$1!=i{print a; a=$2}{i=$1}END{print a}' 

这会在给定索引中构建一串“数据”,然后在索引更改时将其打印出来并开始在新索引上构建下一个字符串,直到该字符串结束......重复......

sed '# label anchor for a jump
   :loop
# load a new line in working buffer (so always 2 lines loaded after)
   N
# verify if the 2 lines have same starting pattern and join if the case
   /^\(\([^|]\)*\(|.*\)\)\n\2/ s//\1/
# if end of file quit (and print result)
   $ b
# if lines are joined, cycle and re make with next line (jump to :loop)
   t loop
# (No joined lines here)
# if more than 2 element on first line, print first line
   /.*|.*|.*\n/ P
# remove first line (using last search pattern)
   s///
# (if anay modif) cycle (jump to :loop)
   t loop
# exit and print working buffer
   ' YourFile
  • posix 版本(在 Mac 上可能是 --posix)
  • 自我评论
  • 假设已排序条目,没有空行,数据中没有管道(也没有转义)
  • 如果可用,将 unbufferd -u用于流进程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM