I have a comma delimited file which I am formatting to create 2 columns using printf. I am using awk to group the contents into similar groups so I can print them into nicely formatted columns.
The formatting works but the contents of the array wrap onto new lines instead of wrapping within the column itself.
Input file example:
1,test,test1,test1
2,test,test1,test2
2,test,test1,test2
2,test,test1,test2
2,test,test1,test2
2,test,test1,test2
2,test,test1,test2
2,test,test1,test2
2,test,test1,test2
2,test,test1,test2
2,test,test1,test2
2,test,test1,test2
2,test,test1,test2`
Command used:
awk -F"," 'NR>1 {a[$3]=a[$3] ? a[$3]", "$4" ("$2")" : $4" ("$2")"}
END {for (i in a) {print i":"a[i]}}' test.dat |
sort |
awk -F":" 'BEGIN { printf "%-15s %-10s\n", "COLUMN1","COLUMN2"; printf "%-15s %-10s\n", "-----------","----------"}
{ printf "%-15s %-10s\n", $1,$2}'
I am also aware about and have tried using column -t -s","
and pr
The outcome is like (simulating example):
COLUMN1 COLUMN2
======== =======
1 test1
2 test2, test2, test2, test2, test2, test2,test2, test2, test2,test2, test2, test2, test2, test2
How can I wrap the second column (even the first one if it is too long) so that it fits within its frame?
COLUMN1 COLUMN2
======== =======
1 test1
2 test2, test2, test2, test2, test2, test2,test2, test2,
test2,test2, test2, test2, test2, test2
Let's pretend this is what your original script is doing given your posted sample input and the output you say you get:
Would that be a good starting point for your question and now you want to wrap each column? If so then I'd take advantage of an existing UNIX tool like
fold
orfmt
to do the wrapping for you so you don't have to write your own code to handle splitting on spaces vs mid-word, etc.:.
If you have a lot of fields that need to be wrapped then it won't be fast due to spawning a subshell for each call to
fold
so here's an all awk version that splits at spaces when possible, test it for edge cases and massage to suit:Here's a version that uses perl instead of awk:
Example:
The magic here is doing the line wrapping using an output format's fill mode. Adjust the width as needed by adding more
<
's to the obvious parts in theformat
description.