Home > Software engineering >  How to format table with awk printf?
How to format table with awk printf?

Time:12-19

How to make print column perfectly align with formatted table?

  | awk 'BEGIN { FS = "_,,,_"
    printf "%-10s | %-10s | %-10s \n", "Date", "Tag", "Name"  } ;
    {
    date=strftime("%Y-%m-%d  %H:%M",$2) ;
    printf "%-10s | %-10s | %-10s \n", date, $1, $3
    }' | column -t -s "|"

The firs proble was that column utterly misaligned and the reason for the misalignment is lengths of words in column are very different. So For a quick-and-dirty fix, I pipe it through column, Is there way to create table with this setup?

This is the output of the code

Date                 Tag                           Name
2020-11-11  06:12    foo                           foo
2020-11-11  06:12    bar                           something-with-a-longer-name
2020-11-11  06:12    something-with-a-longer-name  bar

Expected output

_____________________________________________________________________________________
| Date                | Tag                          | Name                         |
|-----------------------------------------------------------------------------------|
| 2020-11-11  06:12   | foo                          | foo                          |
| 2020-11-11  06:12   | bar                          | something-with-a-longer-name |
| 2020-11-11  06:12   | something-with-a-longer-name | bar                          |
-------------------------------------------------------------------------------------

CodePudding user response:

You might want to try Miller (available here for many OSs):

mlr --itsvlite --ifs '_,,,_' --hi --opprint --barred put '                                                                                
    $* = {
        "Date": strftime($2,"%Y-%m-%d  %H:%M"),
        "Tag": $1,
        "Name": $3
    }
' input_file

With an input file like yours:

foo_,,,_1605075121_,,,_foo
bar_,,,_1605075122_,,,_something-with-a-long-name
something-with-a-longer-name_,,,_1605075123_,,,_bar

That will output:

 ------------------- ------------------------------ ---------------------------- 
| Date              | Tag                          | Name                       |
 ------------------- ------------------------------ ---------------------------- 
| 2020-11-11  06:12 | foo                          | foo                        |
| 2020-11-11  06:12 | bar                          | something-with-a-long-name |
| 2020-11-11  06:12 | something-with-a-longer-name | bar                        |
 ------------------- ------------------------------ ---------------------------- 
  • Related