BASH中的Setw和setfill等价物 请告诉我下面的C++代码段的等效BASH代码是什么: std::cout << std::setfill('x') << std::setw(7) << 250;

BASH中的Setw和setfill等价物 请告诉我下面的C++代码段的等效BASH代码是什么: std::cout << std::setfill('x') << std::setw(7) << 250;,bash,setw,Bash,Setw,谢谢你的帮助 如果您在Linux上,它有一个用于此目的的printf程序。其他UNIX变体也可能有 用x填充数值实际上并不适用于它的任何用例,但您可以通过以下方法获得相同的结果: pax> printf "%7d\n" 250 | tr ' ' 'x' xxxx250 它输出带有空格填充的250,然后使用trtranslate实用程序将这些空格转换为x字符 如果您正在寻找一个只有bash的解决方案,您可以从以下开始: pax> n=250 ; echo ${n} 250 pax&

谢谢你的帮助

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

x
填充数值实际上并不适用于它的任何用例,但您可以通过以下方法获得相同的结果:

pax> printf "%7d\n" 250 | tr ' ' 'x'
xxxx250
它输出带有空格填充的250,然后使用
tr
translate实用程序将这些空格转换为
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}"
}
这将产生:

[Hello there         ]
[Hello]
[         Hello there]
[there]
[Hello there_________]
[Hello there . . . . ]
[xxxx250]
您不仅限于打印它们,还可以使用以下行保存变量以备将来使用:

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

您可以按如下方式打印填充:

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中使用

s=$(for i in 1 2 3 4; do printf "x"; done;printf "250")
echo $s
value=250
padchar="x"
padcount=$((7 - ${#value}))
pad=$(eval echo {1..$padcount})
printf "$padchar%.0s" $pad; printf "%d\n" $value
s=$(for i in 1 2 3 4; do printf "x"; done;printf "250")
echo $s