Using printf (or other?) to create variable fixed width text

I would like to use printf (or something else?) to create a line of text that has varying column widths. This will be used to create a fixed width file (with varying column widths). For example, consider variables $1 $2 $3 are equal to a, b, c respectively and they should be printed in column positions 1, 5, 15 respectively so the output would be:
a___b_________c
(ignore the underlines)

I was thinking I could use awk for this but it isn't clear to me how I could use awk without a file input (I just want to be able to pass text or variables).

Any ideas would be greatly appreciated... maybe there's a simple perl command, a combination of multiple print commands, or something else I should be using?

Try regular shell:

printf "%-4s%-10s%s\n" "$1" "$2" "$3"
1 Like

I just figured it out just as you posted. Thanks!!!

Less negative "%s%4s%10s\n" ?

Sorry, but that (post #2) won't yield a FIXED width file - which was part of the request - should the contents of $3 vary. You need to specify the third column output width as well, then.

EDIT: same applies to DGPickett's proposal, should $1 vary in length.

I guess it depends on whether he wants it to spill over right or left.

$ printf '%s%4s%10s\n' 1 2 3
1   2         3
$ printf '%s%4s%10s\n' 1 22 33
1  22        33
$ 

'%1.1s%4.4s%10.10s\n' truncates, freezes last column to pos ?
'%-4.4s%-10.10s%s\n' truncates, freezes first column to pos ?

@RudiC: OP will figure it out, it was just an example. The post was more about using shell's printf instead of an external utility. Besides what if a value is wider than the intended width?

I use cshell and for this task it writes out values to specific column positions and this is what I ended up with:

setenv ST 06 #Position 1
setenv CTY 001 #Position 3
setenv FIREID CS000000001.1 #Position 6
setenv PTID 1 #Position 21
setenv STACKID 1 #Position 36
setenv SCC 2801500000 #Position 102
setenv LAT 33.19200012 #Position 231
setenv LON -93.7975012 #Position 240
printf "%-2s%-3s%-15s%-15s%-66s%-129s%-9.9s%-9.9s%s\n" $ST $CTY $FIREID $PTID $STACKID $SCC $LAT $LON

Although now I wonder if it is possible to align output to the right of the field rather than the left. For instance if ST is 6 (rather than 06), the first two spaces of output are "6 "rather than " 6". Is there a way to make it align right instead?

Thank you everyone for your very informative posts.

Just leave out the "-" sign and a field will right align...

Hah! I wondered what that negative sign was doing... Thank you very much!!

The printf thinks all strings are numbers, so everything is right jusified unless '-'.