KornShell Printf - Padding a string

14,965

Solution 1

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      '

Solution 2

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

Share:
14,965
C. Ross
Author by

C. Ross

I'm a professional software engineer, with a background in Android, C#, and Java systems throughout the stack, and experience in several industries.

Updated on June 04, 2022

Comments

  • C. Ross
    C. Ross almost 2 years

    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.