为BASH中的单词数组加边框



我一直在学习Bash,我的老师做了一个让我困惑的练习。

我正在努力在单词前面添加空格。

代码应该考虑到每个单词的字符数量,并调整星号和空格的数量,使其始终对齐。

应该是这样的:

***********
* Hello   *
* World   *
* good    *
* etceter *
***********

我代码:

#determine biggest word
words=("Hello" "World" "good" "etceter")
numchar=0
for i in ${words[@]}; do
if [ ${#i} -gt $numchar ]
then
numchar=${#i}
fi
done
#write *
a=-4
while [ $a -lt $numchar ]; do
printf "*"
((a++))
done
#write array
echo
for txt in ${words[@]}; do
space=$(($numchar-${#txt}))
s=0
echo "* $txt "
while [ $s -lt $space ]; do
printf " "
((s++))
printf "*"
done
done
#write *
a=-4
while [ $a -lt $numchar ]; do
printf "*"
((a++))
done

我正在努力与#写数组部分。

提前感谢!

你只需要做一些改动。

#write array
echo
for txt in ${words[@]}; do
space=$(($numchar-${#txt}))
s=0
echo -n "* $txt "           # -n added to not append a newline
while [ $s -lt $space ]; do
echo -n " "             # switched from printf to echo (cosmetics)
((s++))
# printf "*"            # commented out
done
echo "*"                    # added
done

您的while循环只在当前单词后面添加空格。末尾的*在循环之后结束这一行。

改写后三段:

# define solid string of asterisks
printf -v stars  '*%.0s' $(seq 1 $(( numchar + 4)) )    # length = numchar + 4
echo "${stars}"
for txt in "${words[@]}"
do
printf "* %-*s *n" "${numchar}" "${txt}"
done
echo "${stars}"

由此产生:

***********
* Hello   *
* World   *
* good    *
* etceter *
***********

这是硬编码,但我想你已经明白了:

$ echo '***********'; printf '* %-8s*n' "${words[@]}"; echo '***********'
***********
* Hello   *
* World   *
* good    *
* etceter *
***********

您首先获得最长行的长度是正确的。

边框和填充可以完全用printf格式说明符和模式替换来完成。使用%-Ns左对齐,%Ns右对齐。

通过正确的引号,每行也可以有多个单词和空格。

下面是一个例子:

lines=('Hello World!'
'Line two.'
a-line
'another line'
'The end.')
# border character
c='*'
# get length of longest line, required for padding
for i in "${lines[@]}"; do
((${#i} > pad)) &&
pad=${#i}
done
# make a string to fill top/bottom
fill=$(printf %$((pad + 4))s "$c")
fill=${fill// /$c}
# print the text box
printf '%sn' "$fill"
for line in "${lines[@]}"; do
printf "$c %-${pad}s $cn" "$line"
done
printf '%sn' "$fill"

输出:

****************
* Hello World! *
* Line two.    *
* a-line       *
* another line *
* The end.     *
****************

相关内容

  • 没有找到相关文章

最新更新