优化粘贴循环

时间:2014-03-04 09:05:19

标签: bash unix optimization for-loop

我在/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
...

我需要从所有文件中删除第1列 - 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 ...
... ... ...

2 个答案:

答案 0 :(得分: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错误。

答案 1 :(得分:0)

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

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

因此,您可以编写一个脚本来初始化所有文件的命令,最后执行命令。 希望这很有用。