使用 bash 打印表格数据以适合屏幕宽度
Printing Tabular data using bash to fit the screen width
我正在打印使用我的 bash 脚本处理的文件的名称。因为正在处理许多文件路径。我决定让它们的打印类似于 ls
命令,该命令根据屏幕宽度打印表格。但我不知道我的屏幕上可以有多少列,而且在显示器上可能完全不同,有没有自动的方法来做到这一点?或计算宽度并将其与字符串大小进行比较的简单函数...
printf "%s\t" "$FILENAME"
通常这项工作是使用 tput
程序完成的,如下所示:
#!/bin/sh
columns=$(tput cols)
lines=$(tput lines)
printf "terminal dimensions are: %sx%s\n" "$columns" "$lines"
要确定字符串中的字符数,请执行以下操作:
#!/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"
在 Bash 中,您可以从 COLUMNS
和 LINES
内置变量中获取屏幕宽度和高度。
如另一个答案中所述,您可以使用 ${#var}
.
获取 Bash 中字符串的长度
您可能会发现古老而古老的 pr
实用程序可用于生成列中的输出。
我正在打印使用我的 bash 脚本处理的文件的名称。因为正在处理许多文件路径。我决定让它们的打印类似于 ls
命令,该命令根据屏幕宽度打印表格。但我不知道我的屏幕上可以有多少列,而且在显示器上可能完全不同,有没有自动的方法来做到这一点?或计算宽度并将其与字符串大小进行比较的简单函数...
printf "%s\t" "$FILENAME"
通常这项工作是使用 tput
程序完成的,如下所示:
#!/bin/sh
columns=$(tput cols)
lines=$(tput lines)
printf "terminal dimensions are: %sx%s\n" "$columns" "$lines"
要确定字符串中的字符数,请执行以下操作:
#!/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"
在 Bash 中,您可以从 COLUMNS
和 LINES
内置变量中获取屏幕宽度和高度。
如另一个答案中所述,您可以使用 ${#var}
.
获取 Bash 中字符串的长度
您可能会发现古老而古老的 pr
实用程序可用于生成列中的输出。