2010-08-12 17 views

回答

4

如果你在Linux上,它只有一个printf程序用于此目的。其他UNIX变体也可能有它。

填充与x数字是不是真的就其使用情况,但你可以得到同样的结果:

pax> printf "%7d\n" 250 | tr ' ' 'x' 
xxxx250 

与空间填充输出250,然后使用tr翻译工具来把这些空格分成x个字符。

如果你正在寻找一个bash - 只解决方案,你可以这样开始:

pax> n=250 ; echo ${n} 
250 

pax> n=xxxxxxx${n} ; echo ${n} 
xxxxxxx250 

pax> n=${n: -7} ; echo ${n} 
xxxx250 

如果你想要一个通用的解决方案,您可以使用此功能fmt,单元测试代码包含:

#!/bin/bash 
# 
# fmt <string> <direction> <fillchar> <size> 
# Formats a string by padding it to a specific size. 
# <string> is the string you want formatted. 
# <direction> is where you want the padding (l/L is left, 
# r/R and everything else is right). 
# <fillchar> is the character or string to fill with. 
# <size> is the desired size. 
# 
fmt() 
{ 
    string="$1" 
    direction=$2 
    fillchar="$3" 
    size=$4 
    if [[ "${direction}" == "l" || "${direction}" == "L" ]] ; then 
     while [[ ${#string} -lt ${size} ]] ; do 
      string="${fillchar}${string}" 
     done 
     string="${string: -${size}}" 
    else 
     while [[ ${#string} -lt ${size} ]] ; do 
      string="${string}${fillchar}" 
     done 
     string="${string:0:${size}}" 
    fi 
    echo "${string}" 
} 

 

# Unit test code. 

echo "[$(fmt 'Hello there' r ' ' 20)]" 
echo "[$(fmt 'Hello there' r ' ' 5)]" 
echo "[$(fmt 'Hello there' l ' ' 20)]" 
echo "[$(fmt 'Hello there' l ' ' 5)]" 
echo "[$(fmt 'Hello there' r '_' 20)]" 
echo "[$(fmt 'Hello there' r ' .' 20)]" 
echo "[$(fmt 250 l 'x' 7)]" 

此输出:

[Hello there   ] 
[Hello] 
[   Hello there] 
[there] 
[Hello there_________] 
[Hello there . . . . ] 
[xxxx250] 

,你就不仅限于打印它们,你也可以用一条线保存变量以后,如:

formattedString="$(fmt 'Hello there' r ' ' 20)" 
+0

完美的工作。非常感谢你! – raytracer 2010-08-12 02:53:42

0

可以打印边距像这样:

printf "x%.0s" {1..4}; printf "%d\n" 250 

如果要概括,不幸的是,你将不得不使用eval

value=250 
padchar="x" 
padcount=$((7 - ${#value})) 
pad=$(eval echo {1..$padcount}) 
printf "$padchar%.0s" $pad; printf "%d\n" $value 

您可以直接在ksh中的大括号序列表达式中使用变量,但不能使用Bash。

-1
s=$(for i in 1 2 3 4; do printf "x"; done;printf "250") 
echo $s 
相关问题