如何打印终端大小的水平线,中间有一个单词?

如何打印终端大小的水平线,中间有一个单词?

我需要显示

--------------------------- word ----------------------------

将单词放在水平线的中间,并将水平线的长度设置为适合所使用的终端宽度。

我考虑过使用类似的表达方式

printf '%*s\n' "$(tput cols)" '' | tr ' ' -

答案1

这是一个版本,但我确信有一种更紧凑的方法

#!/bin/bash

WORD=$@
NUMBER_OF_SPACES_SURROUNDING_THE_WORD=1  

TERMINAL_WIDTH=$(tput cols)
WORD_SIZE=$(echo $WORD | wc -c )
NUMBER_OF_SPACES_SURROUNDING_THE_WORD=1
NUMBER_OF_SYMBOLS=$((TERMINAL_WIDTH -   $WORD_SIZE - 2*$NUMBER_OF_SPACES_SURROUNDING_THE_WORD))
LENGTH_OF_RIGHT_PART=$((NUMBER_OF_SYMBOLS/2 + $NUMBER_OF_SYMBOLS%2 ))
LENGTH_OF_LEFT_PART=$(( $TERMINAL_WIDTH - 2*$NUMBER_OF_SPACES_SURROUNDING_THE_WORD - $WORD_SIZE - $LENGTH_OF_RIGHT_PART      ))


printf '%*s' "$LENGTH_OF_RIGHT_PART" '' | tr " " -
printf '%*s' $NUMBER_OF_SPACES_SURROUNDING_THE_WORD
printf $WORD
printf '%*s' $NUMBER_OF_SPACES_SURROUNDING_THE_WORD
printf '%*s\n' "$LENGTH_OF_RIGHT_PART" '' | tr " " -

相关内容