【问题标题】:Optimize paste loop优化粘贴循环
【发布时间】:2014-03-04 09:05:18
【问题描述】:

我在/myfolder 中有 1000 个文件,每个文件约为 8Mb,并且有 500K 行和 2 列,如下所示:

file1.txt
Col1 Col2
a 0.1
b 0.3
c 0.2
...

file2.txt
Col1 Col2
a 0.8
b 0.9
c 0.4
...

我需要从所有文件中删除第一列 - Col1 并并排粘贴所有文件,文件顺序无关紧要。

我正在运行以下代码,它已经运行了 4 个小时......无论如何要加快速度?

for i in /myfolder/*; do \
paste all.txt <(cut -f2 ${i}) > temp.txt; \
mv temp.txt all.txt; \
done

预期输出:

all.txt
Col2 Col2 ...
0.1 0.8 ... 
0.3 0.9 ...
0.2 0.4 ...
... ... ...

【问题讨论】:

  • 所有文件的第一列是否相同?
  • 是的,所有文件都一样。

标签: bash unix optimization for-loop


【解决方案1】:

我认为如果您并行遍历文件,这项任务会容易得多。对于每个文件的每一行,您只需截取第一部分,然后打印结果的串联。

在 Python 中,类似于

import glob

# Open all *.txt files in parallel
files = [open(fn, 'r') for fn in glob.glob('*.txt')]
while True:
    # Try reading one line from each file, collecting into 'allLines'
    try:
        allLines = [next(f).strip() for f in files]
    except StopIteration:
        break

    # Chop off everything up to (including) the first space for each line
    secondColumns = (l[l.find(' ') + 1:] for l in allLines)

    # Print the columns, interspersing space characters
    print ' '.join(secondColumns)

唉,让allLines 生成器似乎不起作用 - 由于某种原因,next 调用不会引发 StopIteration 错误。

【讨论】:

    【解决方案2】:

    我不会完全回答。但如果你尝试这个,你可能会成功。 例如:- 根据第一列合并 4 个文件:

    join -1 1 -2 1 temp1 temp2 | join - temp3|join - temp4
    

    因此,您可以编写一个脚本以最初使用所有文件构建命令,最后执行该命令。 希望这有用。

    【讨论】:

    • 我们是否建议joinpaste 更有效?此外,文件没有排序。
    猜你喜欢
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    • 2019-12-27
    相关资源
    最近更新 更多