[英]How to make a blinking printf command (using tput) stop manually after a while in bash (Ubuntu 18.04)?
[英]How to format columns with printf in bash when tput is used
使用tput會更改字符串的長度,因此列不會對齊。 如何解決這個問題?
嘗試使用bash腳本中的以下代碼。
B="$(tput bold)" # Bold text
N="$(tput sgr0)" # Normal text
function testing(){
IN="KEYS | VALUES | DESCRIPTION
id | ${B}10${N} or ${B}20${N} | Enter ID. Default is ${B}10${N}.
status | ${B}true${N} or ${B}false${N} | Enter status of something. Default is ${B}true${N}.
style | Example: Standard | Give suitable standard."
IFS=
while read -r lines; do
IFS='|' read -r -a array <<< "$lines"
printf "%-35s %-35s %-s\n" "${array[0]}" "${array[1]}" "${array[2]}"
done <<< "$IN"
read -p "$*"
exit 0
}
輸出類似於:
KEYS VALUES DESCRIPTION
id **10** or **20** Enter ID. Default is **10**.
status **true** or **false** Enter status of something. Default is **true**.
style Example: Standard Give suitable standard.
預計將是:
KEYS VALUES DESCRIPTION
id **10** or **20** Enter ID. Default is **10**.
status **true** or **false** Enter status of something. Default is **true**.
style Example: Standard Give suitable standard.
正如我在評論中提到的那樣:
DESCRIPTION
字符串會丟失20個縮進空格 ${#B}
#B ${#B}
和${#N}
)分別為4和6個字符 VALUES
字段中出現兩次,總共20個(不可打印)字符 printf/%s
計數20不可打印字符作為輸出因此外觀20個空間“丟失”(即,部分printf
是印刷35個字符...它只是那些字符的20非印刷) 如果我們測量第二個字段的長度 - 有和沒有特殊字符 - 然后使用差異(即,不可打印字符的數量)來增加printf
命令的第二個字段的格式寬度怎么辦?
我們將第二個字段的長度(包括我們的特殊字符)存儲在一個新變量len2
:
len2="${#array[1]}"
接下來,我們要刪除特殊字符並測量結果字符串的長度並放置在變量lenx
:
x="${array[1]//${B}/}" # strip out all occurrences of variable 'B'
x="${x//${N}/}" # strip out all occurrences of variable 'N'
lenx=${#x}
注意:我有一些問題,讓tr
和sed
正確刪除特殊字符; 我願意接受建議。 從好的方面來說......我不會產生任何子流程。
我們將新格式寬度存儲在變量w2
('w'width for field'2')中,如下所示:
w2=$(( 35 + len2 - lenx ))
並且新的printf
格式字符串變為:
printf "%-35s %-${w2}s %-s\n" ...
將它們全部拉到一起我們得到:
B="$(tput bold)" # Bold text
N="$(tput sgr0)" # Normal text
function testing(){
IN="KEYS | VALUES | DESCRIPTION
id | ${B}10${N} or ${B}20${N} | Enter ID. Default is ${B}10${N}.
status | ${B}true${N} or ${B}false${N} | Enter status of something. Default is ${B}true${N}.
style | Example: Standard | Give suitable standard."
IFS=
while read -r lines; do
IFS='|' read -r -a array <<< "$lines"
len2="${#array[1]}"
x="${array[1]//${B}/}"
x="${x//${N}/}"
lenx=${#x}
w2=$(( 35 + len2 - lenx ))
# echo "w2 = ${w2}"
printf "%-35s %-${w2}s %-s\n" "${array[0]}" "${array[1]}" "${array[2]}"
done <<< "$IN"
read -p "$*"
exit 0
}
在我的bash環境中運行腳本會生成:
$ testing
KEYS VALUES DESCRIPTION
id 10 or 20 Enter ID. Default is 10.
status true or false Enter status of something. Default is true.
style Example: Standard Give suitable standard.
注意:粗體字段在我的終端上以粗體顯示 ...它們不會在上面的答案中以粗體顯示/顯示。
如果你取消注釋行 - echo "w2 = ${w2}"
- 你應該找到(對於2條感興趣的行),我們將使用第二個字段的格式寬度55
(即所需的35
加上一個額外的20
來補償20個字符的不可打印的字符)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.