2015-10-06 66 views
0

我正在打印使用bash腳本處理的文件的名稱。因爲有很多文件路徑正在處理中。我決定將它們打印成類似於ls命令,其打印關於屏幕寬度的表格。但我不知道在屏幕上可以顯示多少列,並且在顯示器上可以完全不同,有沒有自動的方法可以做到這一點?使用bash打印表格數據以適合屏幕寬度

#!/bin/sh 

columns=$(tput cols) 
lines=$(tput lines) 

printf "terminal dimensions are: %sx%s\n" "$columns" "$lines" 

要確定數量:或者一個簡單的功能,將計算寬度,並將其與琴絃的大小...

printf "%s\t" "$FILENAME" 

回答

2

一般來說,這工作是使用tput程序做如下在你的字符串的字符如下操作:

#!/bin/sh 

MYSTRING="This a long string containing 38 bytes" 

printf "Length of string is %s\n" "${#MYSTRING}" 

趁着shell的測量與${#var}串的能力。 這裏是把這些技術一起格式化和中心文本的示例:

#!/bin/sh 

columns=$(tput cols) 
lines=$(tput lines) 
string="This text should be centered" 
width="${#string}" 
adjust=$(((columns - width)/2)) 
longspace="            " 

printf "%.*s" "$adjust" "$longspace" 
printf "%s" "${string}" 
printf "%.*s" "$adjust" "$longspace" 
printf "\n" 
1

在bash,那麼你可以從COLUMNSLINES內置變量的畫面寬度和高度。
正如另一個答案中所述,您可以通過使用${#var}來獲取Bash中字符串的長度。
您可能會發現古老而古老的pr實用程序對於在列中生成輸出很有用。