选项卡分隔文本转换为带边框的表格格式

时间:2009-05-12 14:38:55

标签: csv file-format tabular

我需要将制表符分隔文本文件转换为表格格式,如下所示

文件内容

ID<TAB>WorkId<TAB>Date
0<TAB>W-1230699600000<TAB>2008-12-31
1<TAB>W-1233378000000<TAB>2009-01-31

需要成为

+--------+-----------------+-------------+
| ID     | WorkId          | Date        |
+--------+-----------------+-------------+
| 0      | W-1230699600000 | 2008-12-31  |
| 1      | W-1233378000000 | 2009-01-31  |
+--------+-----------------+-------------+

2 个答案:

答案 0 :(得分:1)

我最终使用awk来做到这一点。这就是我所做的。

cat /tmp/1.txt | awk -F'\t' '
BEGIN {
    fieldSize=5;

    for (i=1; i < fieldSize; i++) {
    fLength[i]=0;
    }
}
{
    for (i=1; i <= fieldSize; i++) {
    if (fLength[i] < length($i)) {
            fLength[i] = length($i)
        }

    }
    line[NR]=$0
}
END {
    for (i=1; i <= NR; i++) {
        split(line[i], values, "\t")
        format="| "
        arguments=""
        seperator="+"
        for (j=1; j <= fieldSize; j++) {
        format=format"%-"fLength[j]"s | "
            for (c=0; c <= fLength[j]; c++) seperator=seperator"-"
            seperator=seperator"-+"
            arguments=arguments" \""values[j]"\""
        }

    if (i == 1) print seperator;

        printCommand="printf \""format"\n\" "arguments
        system(printCommand)

    if (i == 1) print seperator;
    }
    print seperator;

}
'

答案 1 :(得分:0)

使用Perl的格式化程序:

#!/usr/bin/perl
open(MYFILE, ">myfile.txt") or die "File does not exist!";

my $id, $workid, $date;

print MYFILE
"+-----+----------+---------------+\n" .
"|ID   |WorkId    |Date           |\n" .
"+-----+----------+---------------+\n";

format MYFILE =
|@<<<<|@<<<<<<<<<|@<<<<<<<<<<<<<<|
 $id    $workid     $date
+-----+----------+---------------+
.

while(<>)
{
  next if (m/^ID/);
  ($id,$workid,$date) = split(/\t/);
  write MYFILE;
}