簡體   English   中英

printf bash-在現有行的中間打印文本,並用標記將其包圍

[英]printf bash - print text in the middle of existing line surrounded by marks

似乎並不那么簡單。 至少對我來說。

我需要在printf文本中有一個變量。 就像這樣:

FOO="User data"
+++++++++++++++++++ $FOO +++++++++++++++++++++

將輸出

+++++++++++++++++++ User Data +++++++++++++++++++++

FOO="Fooooooo barrrr"
+++++++++++++++++++ $FOO +++++++++++++++++++++

應該輸出

++++++++++++++++ Fooooooo barrrr ++++++++++++++++++

FOO="Foooooooooooooooooooo barrrrr"
+++++++++++++++++++ $FOO +++++++++++++++++++++

應該

+++++++++ Foooooooooooooooooooo barrrrr +++++++++++

如您所見,我需要一個變量位於n線的中間,並用+標記包圍。 如何使用printf和其他默認可用命令來實現?

(Debian 8)

declare -i x1 x2 x3 width
foo="User data"
width=50                # total width
x2=${#foo}+2            # length of $foo and 2 whitespaces
x1=(50-x2)/2            # length of first part
x3=$width-x1-x2         # length of last part
for ((i=1;i<=$x1;i++)); do echo -n "+"; done
echo -n " $foo "
for ((i=1;i<=$x3;i++)); do echo -n "+"; done

輸出:

+++++++++++++++++++ User data ++++++++++++++++++++

使用foo="stackoverflow.com"

+++++++++++++++ stackoverflow.com ++++++++++++++++
#!/usr/bin/env bash
linelen=100
char="+"
text=$1
len=$(echo -n $text | wc -m)
fillerlen=$((($linelen - $len - 2) / 2))
filler=$(printf "$char%.0s" $(seq 1 $fillerlen))

echo $filler $text $filler

printf的格式字符串中,可以使用%${p}s指定字符串的“精度”,其中$p是精度。 通過不打印任何內容(擴展到空格)所需的次數,然后將空格轉換為“ +”,您可以利用它:

$ p=10
$ printf "%${p}s\n" | tr ' ' +
++++++++++

此函數將您的行的長度和要放在其中心的字符串取走,然后用加號將其打印出來:

pad () {
    len=$1
    string=$2

    # ${#string} expands to the length of $string
    n_pad=$(( (len - ${#string} - 2) / 2 ))

    printf "%${n_pad}s" | tr ' ' +
    printf ' %s ' "$string"
    printf "%${n_pad}s\n" | tr ' ' +
}

像這樣工作:

$ pad 50 Test
++++++++++++++++++++++ Test ++++++++++++++++++++++
$ pad 50 "A longer string to be padded"
++++++++++ A longer string to be padded ++++++++++

請注意,您必須如何引用由多個單詞組成的字符串,否則將僅使用第一個單詞。

如果行的長度不能被2整除,則填充將向下取整,但始終保持對稱。

嘗試這個 :

#!/bin/bash
n=50; # You can change the value of n as you please.
var="fooo baar";
size=${#var}
n=$(( n - size ))
n=$(( n / 2 ))
s=$(printf "%-${n}s" "*")
echo "${s// /*} "$var" ${s// /*}" #white-spaces included here.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM