سؤال
هل يمكن أن تخبرني من فضلك ما هو رمز bash المكافئ للمقتطف C ++ التالي:
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 ، ولكن ليس باش.
s=$(for i in 1 2 3 4; do printf "x"; done;printf "250")
echo $s