0

我有一个包含几十万行、单列、没有空格、没有引号、没有逗号的 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 方法。这绝对是我的头,所以请帮忙,谢谢。

4

3 回答 3

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希望它打印到标准输出一样运行它,或者也可以在 shell 中将它重定向到一个文件。

于 2013-02-12T18:35:53.377 回答
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"实际文件名。这写入标准输出;如果这是一个问题,您可以打开另一个文件进行写入。

于 2013-02-12T18:36:35.557 回答
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.

于 2013-02-12T19:32:32.720 回答