KornShell Printf-填充字符串 [英] KornShell Printf - Padding a string
问题描述
我正在尝试编写一个KornShell(ksh)函数,该函数使用printf将字符串填充到特定宽度.
I'm attempting to write a KornShell (ksh) function that uses printf to pad a string to a certain width.
示例:
致电
padSpaces Hello 10
输出
'Hello '
我目前有:
padSpaces(){
WIDTH=$2
FORMAT="%-${WIDTH}.${WIDTH}s"
printf $FORMAT $1
}
看来,这本身就是可行的,但是当我在脚本中分配它时,除了第一个空格外,它似乎丢失了所有内容.
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}
输出:
TEST A
我也欢迎不使用printf的建议.我真正想了解的是一种从ksh制作固定宽度文件的方法.
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.
推荐答案
您的功能对我来说很好.您的分配不适用于等号周围的空格.应该是:
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 '
这篇关于KornShell Printf-填充字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!