Как мне напечатать переменную с выравниванием по центру с отступами?

Версия Vi 7.2, на которую вы ссылаетесь, может быть Vim 7.2 (в некоторых системах vi на самом деле vim ). Если это на самом деле Vim, параметр hlsearch должен быть там, если он не был скомпилирован без функции extra_search . Эта функция недоступна, если Vim был скомпилирован с его "крошечным" или "маленьким" набором функций .

Это строго функция Vim, недоступная в Vi.

Ввод : help hlsearch в Vim 8.0 дает мне

'hlsearch' 'hls'        boolean (default off)
                        global
                        {not in Vi}
                        {not available when compiled without the
                        +extra_search feature}

Я предполагаю, что vi в вашей системе на самом деле Vim скомпилирован с небольшим или крошечным набором функций, а vim - это Vim, скомпилированный с большим набором функций.

6
05.03.2016, 02:09
2 ответа

Это предложение кажется функциональным, но подразумевает, что терминал поддерживает возможности terminfo cols, hpa, ech, cufи cud1, ср.tput(1 ), terminfo(5 ), infocmp(1m ).

#!/bin/bash

# Function "center_text": center the text with a surrounding border

# first argument: text to center
# second argument: glyph which forms the border
# third argument: width of the padding

center_text()
{
    local terminal_width=$(tput cols)    # query the Terminfo database: number of columns
    local text="${1:?}"                  # text to center
    local glyph="${2:-=}"                # glyph to compose the border
    local padding="${3:-2}"              # spacing around the text

    local border=                        # shape of the border
    local text_width=${#text}

    # the border is as wide as the screen
    for ((i=0; i<terminal_width; i++))
    do
        border+="${glyph}"
    done

    printf "$border"

    # width of the text area (text and spacing)
    local area_width=$(( text_width + (padding * 2) ))

    # horizontal position of the cursor: column numbering starts at 0
    local hpc=$(( (terminal_width - area_width) / 2 ))

    tput hpa $hpc                       # move the cursor to the beginning of the area

    tput ech $area_width                # erase the border inside the area without moving the cursor
    tput cuf $padding                   # move the cursor after the spacing (create padding)

    printf "$text"                      # print the text inside the area

    tput cud1                           # move the cursor on the next line
}

center_text "Something I want to print" "~"
center_text "Something I want to print" "=" 6

Следующее предложение является надежным, расширяемым и более ясным, чем @ Решение с подстановочным знаком .

#!/bin/bash

# Function "center_text": center the text with a surrounding border

# first argument: text to center
# second argument: glyph which forms the border
# third argument: width of the padding

center_text()
{

    local terminal_width=$(tput cols)     # query the Terminfo database: number of columns
    local text="${1:?}"                   # text to center
    local glyph="${2:-=}"                 # glyph to compose the border
    local padding="${3:-2}"               # spacing around the text

    local text_width=${#text}             

    local border_width=$(( (terminal_width - (padding * 2) - text_width) / 2 ))

    local border=                         # shape of the border

    # create the border (left side or right side)
    for ((i=0; i<border_width; i++))
    do
        border+="${glyph}"
    done

    # a side of the border may be longer (e.g. the right border)
    if (( ( terminal_width - ( padding * 2 ) - text_width ) % 2 == 0 ))
    then
        # the left and right borders have the same width
        local left_border=$border
        local right_border=$left_border
    else
        # the right border has one more character than the left border
        # the text is aligned leftmost
        local left_border=$border
        local right_border="${border}${glyph}"
    fi

    # space between the text and borders
    local spacing=

    for ((i=0; i<$padding; i++))
    do
        spacing+=" "
    done

    # displays the text in the center of the screen, surrounded by borders.
    printf "${left_border}${spacing}${text}${spacing}${right_border}\n"
}

center_text "Something I want to print" "~"
center_text "Something I want to print" "=" 6
0
27.01.2020, 20:25

Для центрирования текста с граничными символами:

center() {
term_width=$(tput cols)
string_width=$(echo "$1" | wc -m)
# echo $term_width $string_width
padding=$(awk "BEGIN {print int(($term_width-$string_width)/2)}")
# echo $padding
len=$padding ch='='
printf '%*s' "$len" | tr ' ' "$ch"; printf "$1"; printf '%*s' "$len" | tr ' ' "$ch"; echo;
}

center " Something I want to print "

Выход:

========================== Something I want to print ==========================

Для печати текста по центру с граничными линиями:

center() {
printf '=%.0s' $(seq 1 $(tput cols))
echo "$1" | sed  -e :a -e "s/^.\{1,$(tput cols)\}$/ & /;ta" | tr -d '\n' | head -c $(tput cols)
printf '=%.0s' $(seq 1 $(tput cols)) | sed 's/^ //'
}

center " Something I want to print "

Выход:

================================================================================
                            Something I want to print                           
================================================================================
0
19.09.2021, 13:27

Теги

Похожие вопросы