如何将单行短数据格式化为带索引的终端表格布局
问题描述
现有一文本文件,每行一条短数据(比如单词或单个数字),没有空行和表头。需要把它转成适配终端宽度的行优先表格,还要给每条数据加上索引。目前用nl --line-increment能实现索引,但存在索引列宽度、列数、最大索引之间的循环依赖问题。现在已有一个固定列数但未对齐的实现命令:
per_line=3; pr -a -${per_line} -t -s\ | nl -v 0 --line-increment ${per_line}
想找更优的简洁实现方案。
解决方案
下面是自动适配终端宽度、且能对齐的带索引表格实现:
分步命令(易读版)
# 计算单条数据的最大长度 max_item_len=$(awk '{print length($0)}' input.txt | sort -nr | head -1) # 计算最大索引的位数(比如总共有100条数据,最大索引是99,位数就是2) max_idx_len=$(echo $(wc -l < input.txt)-1 | bc | wc -c) # 计算每列需要的宽度(索引宽度+分隔空格+数据最大宽度) col_width=$((max_idx_len + 2 + max_item_len)) # 根据终端宽度计算最多能放几列 cols=$(( $(tput cols) / col_width )) # 生成对齐的带索引表格 nl -v 0 -w $max_idx_len -s ' ' input.txt | pr -a -t -s ' ' --columns=$cols | column -t -s ' '
单命令简洁版
cols=$(( $(tput cols) / ($(awk '{print length($0)}' input.txt | sort -nr | head -1) + $(echo $(wc -l < input.txt)-1 | bc | wc -c) + 2) )); nl -v 0 -w $(echo $(wc -l < input.txt)-1 | bc | wc -c) -s ' ' input.txt | pr -a -t -s ' ' --columns=$cols | column -t -s ' '
说明
- 自动根据终端宽度、数据最大长度、最大索引位数计算最优列数,解决了循环依赖问题
nl命令负责生成从0开始的索引,并固定索引列宽度,保证对齐pr实现行优先的多列排列column最终完成所有列的对齐,让表格更规整
内容的提问来源于stack exchange,提问作者einpoklum
相关产品推荐
相关产品推荐

