Reputation: 219
I have a file with data
number name age sex
102234 James_Mckenzie 21 M
102233 Jim_Reil 24 M
102235 Alan_Lightbrighter 19 M
...
and I am trying to print them out in such form
number :
name : age :
sex :
so basically, the printout will be like this,
number : 102233
name : Jim_Reil age : 24
sex : M
number : 102235
name : Alan_Lightbrighter age : 19
sex : M
...
The problem is I am trying to keep up with spacing between name and age, but due to the variable name length, the position of 'age' is not where I am want(I used /t for spacing) What would be the best way to fix this issue?
I am sorry if this has been asked thousand times already.(I spend some time searching but I guess my search keyword sucked :( )
Thanks
Upvotes: 0
Views: 426
Reputation: 881993
Don't use tabs for spacing since that relies entirely on the vagaries of your terminal.
Figure out what the largest name is likely to be and use printf
with a %-50s
format specifier (50 characters wide, left justified) on your name, as per the following transcript:
$ echo '1 pax X
2 paxdiablo_with_a_very_long_name Y' | awk '{printf "%3d %-40s %s\n",$1,$2,$3}'
1 pax X
2 paxdiablo_with_a_very_long_name Y
Or, closer to your requirements:
$ echo '102234 James_Mckenzie 21 M
102233 Jim_Reil 24 M
102235 Alan_Lightbrighter 19 M' | awk '
{printf "number : %d\nname : %-20s age : %d\nsex : %s\n",$1,$2,$3,$4}'
number : 102234
name : James_Mckenzie age : 21
sex : M
number : 102233
name : Jim_Reil age : 24
sex : M
number : 102235
name : Alan_Lightbrighter age : 19
sex : M
Obviously, the 50
and 20
are examples - you should choose a size that suits your needs. If necessary, you could even go through the file on the first pass to work out the largest name and then use a format string constructed from that in a second pass to print, but that's probably overkill.
Upvotes: 1