RizoToma Totta
RizoToma Totta

Reputation: 51

Printing columns and their headers using awk

I am trying to set titles for columns in my table and i used this code below:

$ awk 'BEGIN {print "Name\tDescription\tType\tPrice";}
> {print $1,"\t",$2,"\t",$3,"\t",$4,"\t",$NF;}
> END{print "Report Generated\n--------------";
> }' toys | column -s '/' -t

I have tried this code als, but I don't understand the sytax and the implementation there:

$ awk 'BEGIN {print "Name\tDescription\tType\tPrice";}
> {printf "%-24s %s\n", $1,$2,$3,$NF;}

> }' toys 

The data and results that I want to have:

The table contains:

 Mini car Kids under 5 Wireless 2000
 Barbie   Kids 6 - 12  Electronic 3000
 Horse    Kids 6 -8    Electronic 4000
 Gitar    12 -16       ELectronic 45000 

When I print the above command it gives me this output:

 Name    Description  Type   Price
 Mini car    Kids under 5     Wireless 2000
 Barbie    Kids 6 - 12  Electronic 3000
 Horse    Kids 6 -8    Electronic 4000
 Gitar    12 -16       ELectronic 45000

I want help to print them like that:

 Name        Description    Type       Price
 Mini car    Kids under 5   Wireless   2000
 Barbie      Kids 6 - 12    Electronic 3000
 Horse       Kids 6 -8      Electronic 4000
 Gitar       12 -16         ELectronic 45000

Upvotes: 0

Views: 2097

Answers (1)

Barmar
Barmar

Reputation: 780798

You need a formatting operator for each value that's being printed. Since you're printing 4 columns, you need 4 formatting operators, to specify the width of each column.

$ awk 'BEGIN {printf("%-10s %-15s %-10s %s\n", "Name", "Description", "Type", "Price");}
> {printf("%-10s %-15s %-10s %d\n", $1, $2, $3, $4)}
> }' toys 

`%s` is for printing strings, `%d` is for printing integers.

Upvotes: 1

Related Questions