如何在该 bash 脚本创建的框中间添加 * ?

如何在该 bash 脚本创建的框中间添加 * ?

如何将 a 添加*到此 bash 脚本创建的框的中间?

#!/bin/bash
#
# raami joonistamine
echo -n "sisesta ridade arv: "
read rida
echo -n "sisesta tärnide arv: "
read tarn
# genereeri rea numbrid
for ((i = 1; i <= $rida;i++))
do
    echo -n "$i "
    # kui on esimene või viimane rida
    if [ $i -eq 1 -o $i -eq $rida ]; then
    # tärnidest tulev rida
    for((j = 1; j <=$tarn; j++))
    do
        echo -n "* "
    done
# teised read
    else
        echo -n "* "
        # tühikud
        for((j = 2; j < $tarn;j++))
        do
            echo -n "  "
        done
    echo -n "* "
    fi
    echo
done

答案1

改变你的最内层循环:

# tühikud
for((j = 2; j < $tarn;j++))
do
    echo -n "  "
done

# tühikud
for((j = 2; j < $tarn;j++))
do
    if [ "$i" -eq "$(( (rida+1) / 2 ))" ] && [ "$j" -eq "$(( (tarn+1) / 2 ))" ]; then
        echo -n '* '
    else
        echo -n "  "
    fi
done

也就是说,当您检测到要输出最中间的字符时,插入 a*而不是空格。

对于行中稍微更精确的位置:

# tühikud
for((j = 2; j < $tarn;j++))
do
    if [ "$i" -eq "$(( (rida+1) / 2 ))" ] && [ "$j" -eq "$(( (tarn+1) / 2 ))" ]; then
        if [ "$(( tarn%2 ))" -eq 0 ]; then
            echo -n ' *'
        else
            echo -n '* '
        fi
    else
        echo -n "  "
    fi
done

不要输出单个字符,而是一次输出整行。这样效率更高,并且您只需要关心三种类型的行:顶部/底部行、中间行和其他行:

#!/bin/bash

read -r -p 'Height: ' rows
read -r -p 'Width : ' cols

topbottom=$( yes '*' | head -n "$cols" | tr '\n' ' ' )
printf -v midrow '*%*s*%*s*' "$(( cols - 2 ))" "" "$(( cols - 2 ))" ""
printf -v otherrows '*%*s*' "$(( 2*(cols - 2) + 1 ))" ""

for (( row = 0; row < rows; ++row )); do

    if (( row == 0 )) || (( row == rows - 1 )); then
        thisrow=$topbottom
    elif (( row == rows / 2 )); then
        thisrow=$midrow
    else
        thisrow=$otherrows
    fi

    printf '%2d %s\n' "$(( ++n ))" "$thisrow"
done

相关内容