C. Ross
C. Ross

Reputation: 31848

KornShell Printf - Padding a string

I'm attempting to write a KornShell (ksh) 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 ksh.

Upvotes: 3

Views: 15820

Answers (2)

Dennis Williamson
Dennis Williamson

Reputation: 360325

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      '

Upvotes: 5

Stephan202
Stephan202

Reputation: 61549

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.)

Upvotes: 2

Related Questions