次の C++ スニペットに相当する BASH コードを教えてください。
std::cout << std::setfill('x') << std::setw(7) << 250;
出力は次のとおりです。
xxxx250
助けてくれてありがとう!
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)"
次のようにパディングを印刷できます。
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