views:

1556

answers:

2

I'm attempting to write a Korn Shell function that uses printf to pad a string to a certain width.

Examples:

Call

padSpaces Hello 10

Output

'Hello     '

I currently have:

padSpaces(){
        WIDTH=$2
        FORMAT="%-${WIDTH}.${WIDTH}s"
        printf $FORMAT $1
}

Edit: This seems to be working, in and of itself, but when I assign this in the script it seems to lose all but the first space.

TEXT=`padSpaces "TEST" 10`
TEXT="${TEXT}A"
echo ${TEXT}

Output:

TEST A

I'm also open to suggestions that don't use printf. What I'm really trying to get at is a way to make a fixed width file from kshell.

+1  A: 

Are you aware that you define a function called padSpaces, yet call one named padString? Anyway, try this:

padString() {
    WIDTH=$2
    FORMAT="%-${WIDTH}s"
    printf $FORMAT $1
}

Or, the more compact:

padString() {
    printf "%-${2}s" $1
}

The minus sign tells printf to left align (instead of the default right alignment). As the manpage states about the command printf format [ arg ... ],

The arguments arg are printed on standard output in accordance with the ANSI-C formatting rules associated with the format string format.

(I just installed ksh to test this code; it works on my machineTM.)

Stephan202
This doesn't work on my machine, giving me 0.000000s.
C. Ross
Very odd. Unless `$2` contains some non-digit character (which it doesn't, in your example), I fail to see how `printf` can format the argument as a float instead of a string...
Stephan202
I figured that out, was missing some quotes, but still having an issue, see the above.
C. Ross
+2  A: 

Your function works fine for me. Your assignment won't work with spaces around the equal sign. It should be:

SOME_STRING=$(padSpaces TEST 10)

I took the liberty of replacing the backticks, too.

You don't show how you are using the variable or how you obtain the output you showed. However, your problem may be that you need to quote your variables. Here's a demonstration:

$ SOME_STRING=$(padSpaces TEST 10)
$ sq=\'
$ echo $sq$SOME_STRING$sq
'TEST '
$ echo "$sq$SOME_STRING$sq"
'TEST      '
Dennis Williamson
@Dennis - +1, can you say why the spaces 'get eaten'?
martin clayton
When `ksh` does field splitting (aka word splitting in `bash`), sequences of characters in $IFS are treated as one delimiter when unquoted. Try this: `string==$'a b\t\tc\n\nd'; echo $string; echo "$string"`. The first `echo` will give you "a b c d" and the second one will have a, b, and c spread out and d two lines below. The default value of `$IFS` is `$' \t\n'`.
Dennis Williamson
There should be four spaces between a and b in the assignment to `string` in my previous comment. In this case StackOverflow at them!
Dennis Williamson