Если вы работаете в Linux, для этой цели есть программа printf
.Другие варианты UNIX также могут иметь его.
Заполнение числа с x
на самом деле не относится к его случаям использования, но вы можете получить тот же результат с:
pax> printf "%7d\n" 250 | tr ' ' 'x'
xxxx250
, который выводит250 с пробелом, затем использует утилиту перевода tr
, чтобы превратить эти пробелы в x
символов.
Если вы ищете решение bash
only, вы можете начать с:
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)"