I need to create a markdown formatted output using awk which is similar to table results that we get using mysql. In other words, I'm trying to mimic https://www.convertcsv.com/csv-to-markdown.htm using the below input.
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
The output I'm looking for is below
------------------------------
|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 |
------------------------------
My first attempt is to get the max size for each column and use that in the formatting when printing. But the below one is not working as expected.
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
How to fix it and get the required output.