Formatting output with printf: truncating or padding

Viewed 8806

I would like to produce the following output:

> Avril Stewart  99  54
> Sally Kinghorn 170 60
> John Young     195 120
> Yutte Schim... 250 40

As you can see, names shorter than 14 characters are padded with spaces. Names longer than 15 characters are truncated: 'Yutte Schimmelpenninck' truncates to 'Yutte Schim...'.

Here is what I have tried to achieve this (the variables $name, $height, and $weight are extracted from files, and a loop runs the printf command on each file data):

printf '%-14s -%3s -%3s\n' "$name" "$height" "$weight"
> Avril Stewart  99  54
> Sally Kinghorn 170 60
> John Young     195 120
> Yutte Schimmelpenninck 250 40

A printf one-liner is the desired solution.

What code will produce the first block of output?

3 Answers

This is a partial answer -- Ignoring the final "...":

awk '{printf "%-14.14s %-3d %-3d\n",$1 FS $2,$3,$4}'

where %-14.14s does the padding + truncate formating of the name

Related