【发布时间】:2021-08-11 15:34:59
【问题描述】:
我需要使用 awk 创建一个降价格式的输出,这类似于我们使用 mysql 获得的表结果。换句话说,我试图模仿https://www.convertcsv.com/csv-to-markdown.htm 使用以下输入。
id|type|cost|date|ship
0|A|223|201603|PORT
0|A|22|201602|PORT
0|A|422|201601|DOCK
1|B|3213|201602|DOCK
1|B|3213|201601|PORT
2|C|2321|201601|DOCK
我正在寻找的输出如下
------------------------------
|id |type |cost | date |ship |
------------------------------
|0 |A |223 |201603 |PORT |
|0 |A |22 |201602 |PORT |
|0 |A |422 |201601 |DOCK |
|1 |B |3213 |201602 |DOCK |
|1 |B |3213 |201601 |PORT |
|2 |C |2321 |201601 |DOCK |
------------------------------
我的第一次尝试是获取每列的最大大小,并在打印时在格式中使用它。但是下面的没有按预期工作。
awk -F"|" '
NR==1 { hdr=$0; for(i=1;i<=NF;i++) { a[i]=length($i) } next }
{ for(i=1;i<=NF;i++) { ;a[i]=length($i)>a[i]?length($i):a[i] } content[NR]=$0 }
END {
for(i in a) len+=a[i]+2;
$0=""; OFS="-"; len++; NF=len; print ;
n=split(hdr,arr,FS);
for(i=1;i<=n;i++)
{ printf("%6s |",arr[i]); } # instead of 6 i want to pass a[i] ==> "%6" a[i] "s |" is not working
print "";
}
' data.txt
如何修复它并获得所需的输出。
【问题讨论】: