awk 语句打印 char 变量次数不起作用

awk 语句打印 char 变量次数不起作用

我有以下内容可以根据 csv 文件的最长行打印虚线:

awk -F ',' '
    BEGIN {
       longest_line=0
        for (i = 1; i <= NF; i++) {
           longest[i] = ""
        }
    }
    {
       for (i = 1; i <= NF; i++) {
           if (length($i) > length(longest[i])) {
               longest[i] = $i
           }
       }
    }
    
    END {
        for (i=1; i<=NF;i++) {
            longest_line += length(longest[i])
        }
        printf("%*s", longest_line, "=")
    }
'

这是整个脚本:

awk -F ',' -v smso="$smso" -v rmso="$rmso" 'BEGIN {
    count=1
    firstcol=0
    arraylen=1
    longest_line=0
   for (i = 1; i <= NF; i++) {
       longest[i] = ""
    }
}

{
    for (i=1;i<=NF;i++) {
            if (i==NF) {
                data[arraylen++]=$i
                data[arraylen++]="\n"
            } else {
                data[arraylen++]=$i
            }
    }
}


{
   for (i = 1; i <= NF; i++) {
       if (length($i) > length(longest[i])) {
           longest[i] = $i
       }
   }
}

END {
    for (i=1; i<=NF;i++) {
        longest_line += length(longest[i])
    }
    printf("%*s", longest_line, "b")
    for (i = 1; i <= length(data); i++) {
        if (data[i]=="\n") {
            firstcol++
           count=1  
            printf("%s", data[i])
        } else if (count==1 && i != 1) {
            printf("%s%s%s", "|", data[i], "|")
            count++
        } else {
            smso=$(tput smso)
            rmso=$(tput rmso)
            num_spaces=(length(longest[count])-length(data[i]))+1
            printf("%s%*s%s%s", (i==1?"|":""), (i==1?num_spaces-1:num_spaces), " ", firstcol==0?toupper(data[i]):data[i], "|")
            count++
        }
    }   
}'

输入文件是:

NUMBER,FNAME,LNAME,PHONE-TYPE:GROUPS
222-222-2222,Elizabeth,Taylor,office:beauty:
111-111-1111,Matt,Alex,personal:superhuman:cool:amazing:extra

期望的输出是:

==============================================================
|      NUMBER|     FNAME|  LNAME|           PHONE-TYPE:GROUPS|
|222-222-2222| Elizabeth| Taylor|              office:beauty:|
|111-111-1111|      Matt|   Alex| personal:cool:amazing:extra|

但我的输出是:

                                                             =
|      NUMBER|     FNAME|  LNAME|           PHONE-TYPE:GROUPS|
|222-222-2222| Elizabeth| Taylor|              office:beauty:|
|111-111-1111|      Matt|   Alex| personal:cool:amazing:extra|

答案1

sprintf("%*s", n, string)将字符串左填充到长度(字节数或字符数,具体取决于实现 awkn 有空格

要重复一个字符串 n 次,您可以编写一个辅助函数:

function repeat(n, string,  result) {
  while (n-- > 0) result = result string
  return result
}

在这里,我建议使用mlrwhich 来做到这一点(或类似的东西)开箱即用(并正确处理 CSV):

$ mlr --c2p --barred cat file.csv
+--------------+------------+--------+---------------- ------------------------+
|数字       |名称     |名称  |电话类型:群组                      |
+--------------+------------+--------+---------------- ------------------------+
| 222-222-2222 | 222-222-2222伊丽莎白 |泰勒|办公室:美容: |
| 111-111-1111 |马特|亚历克斯 |个人:超人:酷:惊人:额外 |
+--------------+------------+--------+---------------- ------------------------+

或者对于右对齐字段:

$ mlr --c2p --barred --right cat file.csv
+--------------+------------+--------+---------------- ------------------------+
|       数字|     名称|  名称|                      电话类型:群组|
+--------------+------------+--------+---------------- ------------------------+
| 222-222-2222 | 222-222-2222伊丽莎白 |泰勒|办公室:美容: |
| 111-111-1111 |马特|亚历克斯 |个人:超人:酷:惊人:额外 |
+--------------+------------+--------+---------------- ------------------------+

如果mlr不可用,awk我会使用perl很大程度上已被取代的,而不是awk

perl -MList::Util=zip -MTerm::ANSIColor -F, -lane '
  push @rows, [@F];
  $i = 0; for (@F) {
    $max[$i] = length if length > $max[$i];
    $i++;
  }
  
  END {
    $line = join("+", "", (map {"-" x ($_ + 2)} @max), "");
    print $line;
    print join("|", "", (map {colored(sprintf(" %*s ", @$_), "bold blue")} zip(\@max, shift @rows)), "");
    print $line;
    for (@rows) {
      print join("|", "", (map {sprintf " %*s ", @$_} zip(\@max, $_)), "");
    }
    print $line;
  }' file.csv

这使:

+--------------+-----------+--------+----------------------------------------+
|       NUMBER |     FNAME |  LNAME |                      PHONE-TYPE:GROUPS |
+--------------+-----------+--------+----------------------------------------+
| 222-222-2222 | Elizabeth | Taylor |                         office:beauty: |
| 111-111-1111 |      Matt |   Alex | personal:superhuman:cool:amazing:extra |
+--------------+-----------+--------+----------------------------------------+

标题为粗体和蓝色。

在 中perl,重复字符串是通过x重复运算符完成的:"string" x 3 结果为stringstringstringperldoc perlop 详情请参阅。

尽管perl您很少需要重新发明轮子,因为它已经存在了 35 年,但 Perl 模块已经可以用于任何用途。我们已经使用过List::Util具有一些有用的列表操作函数的模块和Term::ANSIColor输出上面的彩色文本,但还有一个Text::CSV处理 CSV 的模块和Text::ASCIITable设置表格格式:

$ perl -MText::CSV=csv -MText::ASCIITable -e '
  $c = csv(in => shift);
  $t = Text::ASCIITable->new;
  $t->setCols(shift @$c);
  $t->addRow($_) for @$c;
  print $t' file.csv
.----------------------------------------------------------------------------.
| NUMBER       | FNAME     | LNAME  | PHONE-TYPE:GROUPS                      |
+--------------+-----------+--------+----------------------------------------+
| 222-222-2222 | Elizabeth | Taylor | office:beauty:                         |
| 111-111-1111 | Matt      | Alex   | personal:superhuman:cool:amazing:extra |
'--------------+-----------+--------+----------------------------------------'

答案2

printf("%*s", longest_line, "=")

打印一个=longest_line-1空格缩进的字符。你想要这个:

line = sprintf("%*s", longest_line, "")
gsub(/ /,"=",line)
print line

FWIW,这就是我使用任何 awk 编写代码来执行您似乎想要执行的操作的方式:

$ cat tst.awk
BEGIN { FS=","; OFS="|"; hdrChar="=" }
{
    for (colNr=1; colNr<=NF; colNr++) {
        val = $colNr
        vals[NR,colNr] = val
        wid = length(val)
        wids[colNr] = (wid > wids[colNr] ? wid : wids[colNr])
    }
}
END {
    for ( colNr=1; colNr<=NF; colNr++ ) {
        row = row hdrChar sprintf("%*s",wids[colNr],"")
    }
    gsub(/ /,hdrChar,row)
    print row hdrChar

    for ( rowNr=1; rowNr<=NR; rowNr++ ) {
        row = ""
        for ( colNr=1; colNr<=NF; colNr++ ) {
            row = row OFS sprintf("%*s",wids[colNr],vals[rowNr,colNr])
        }
        print row OFS
    }
}

$ awk -f tst.awk file
======================================================================
|      NUMBER|    FNAME| LNAME|                     PHONE-TYPE:GROUPS|
|222-222-2222|Elizabeth|Taylor|                        office:beauty:|
|111-111-1111|     Matt|  Alex|personal:superhuman:cool:amazing:extra|

val = $colNr通过更改为val = " " $colNr " "或类似内容,根据您认为合适的情况用空格填充一些字段。

相关内容