【问题标题】:Tab Seperated text converted to tabular format with border制表符分隔的文本转换为带边框的表格格式
【发布时间】:2009-05-12 14:38:55
【问题描述】:

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

文件内容

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  |
+--------+-----------------+-------------+

【问题讨论】:

  • 只是一个小问题 - 如果它是制表符分隔的,它不是 CSV。

标签: csv file-format tabular


【解决方案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;

}
'

【讨论】:

    【解决方案2】:

    使用 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 2010-11-24
      • 1970-01-01
      相关资源
      最近更新 更多