2013-02-12 75 views
0

我有一個包含幾十萬行,單列,不含空格,不含引號和逗號的CSV文件。將行CSV逐行轉換爲逗號CSV的最簡單方法

line1 
line2 
line3 
line4 

我需要它分裂成仍然是1列,但最多50行的每行,用逗號分隔。

所以:

line1,line2,line3,line4 all the way to line50 
line51,line52,line53, all the way to line100 
line101,line102,line103 all the way to line150 

,直到它完成與CSV。

我有FFE,CSVTOOLS,我正在運行Linux,所以真的更喜歡linux方法。 這絕對是我的頭,所以請幫助,謝謝。

+0

python是一個可行的選擇? – themiurgo 2013-02-12 18:12:39

+0

我可以運行py腳本,但我不熟悉Python自己創建一個。 – 2013-02-12 18:15:07

+0

「我有一個CSV文件,沒有逗號」 - 您知道CSV代表**逗號**分隔值嗎? – 2013-02-12 18:18:22

回答

0

我假設你可以運行Perl腳本。我無法保證速度,但根據您提供的詳細信息,它可以完成工作。

#!/usr/bin/perl 

use strict; 
use warnings; 

my $file = $ARGV[0]; 

open(my $fh, "<", $file) or die $!; 

my $cnt = 0; 
while (<$fh>) { 
    ++$cnt; 
    if ($cnt < 50) { 
     $_ =~ tr/\n/,/; 
     print $_; 
    } 
    else { 
     print "$_"; 
     $cnt = 0; 
    } 
} 

close($fh); 

你可以,如果你想讓它打印到標準輸出或只是重定向它的外殼文件太爲perl convert.pl file運行它。

+0

哇謝謝。好吧,把這個保存爲convert.pl並將它作爲perl convert.pl file.csv運行,它會保存爲同一個文件? – 2013-02-12 18:40:07

+0

不,它會打印到終端,只是重定向到另一個文件來保存舊文件。我建議運行'perl convert.pl file.csv> output.csv' – squiguy 2013-02-12 18:41:14

+0

好吧,你的腳本看起來很棒。非常感謝。它在終端中迴響,但是將其保存到另一個.csv文件的最簡單方法是什麼? – 2013-02-12 18:42:50

0

所以你想從一個文件讀取50行,然後連接使用逗號,對吧?下面是我想出(使用Python):

import sys; 

fd = open("foo.txt"); 
for i in range(3): 
    for j in range(50): 
     line = fd.readline().rstrip() 
     if (j != 0): 
      sys.stdout.write(",") 
     sys.stdout.write(line) 
    sys.stdout.write("\n") 
fd.close() 

變化3至50行的塊"foo.txt"數量和實際文件名。這寫入標準輸出;如果這是一個問題,您可以打開另一個文件進行寫作。

0

在bash:

#!/bin/bash 

out_file=output.csv 
line_width=50 

count=0 

while read line 
do 
    echo -n $line >> $out_file 
    count=$(($count+1)) 

    if [ $count -lt $line_width ] 
    then 
    echo -n "," >> $out_file 
    else 
    echo "" >> $out_file 
    count=0 
    fi 
done 

# strip trailing commas 
sed 's/,$//g' < $out_file > "$out_file.tmp" && mv "$out_file.tmp" $out_file

說你wrap.sh有此腳本,通過命令行執行:

$ ./wrap.sh < file.txt

輸出將在output.csv