質問

次の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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top