如何以预定义间距的表格格式写入 bash 命令的输出

How to write output of a bash command in tabular format with a pre-defined spacing

 2   0   0   184
 2   0   0   184
 765311      61423       6454323302  470948
 598500      678403      6454288800  1810469

我用grep <command output> | cut -d ':' -f 3 | column -x >> $temp以表格格式写入数据。但是字符串的长度似乎存在巨大差异,导致 table 倾斜。我需要用等间距格式化这些。我怎样才能做到这一点?

编辑:命令运行的文件包含如下文本:

total_STDIO_OPENS: 176400
total_STDIO_FDOPENS: 0
total_STDIO_READS: 5881999200
total_STDIO_WRITES: 276435
total_STDIO_SEEKS: 0
total_STDIO_FLUSHES: 0
total_STDIO_BYTES_WRITTEN: 7689144
total_STDIO_BYTES_READ: 53954527200
total_STDIO_MAX_BYTE_READ: 917480
total_STDIO_MAX_BYTE_WRITTEN: 176
total_STDIO_FASTEST_RANK: 81759
total_STDIO_FASTEST_RANK_BYTES: 917712
total_STDIO_SLOWEST_RANK: 137230
total_STDIO_SLOWEST_RANK_BYTES: 917729
total_STDIO_F_META_TIME: 235319.135093
total_STDIO_F_WRITE_TIME: 2.271446
total_STDIO_F_READ_TIME: 1204.541221
total_STDIO_F_OPEN_START_TIMESTAMP: 0.000000
total_STDIO_F_CLOSE_START_TIMESTAMP: 0.000000
total_STDIO_F_WRITE_START_TIMESTAMP: 6.714122
total_STDIO_F_READ_START_TIMESTAMP: 0.000000
total_STDIO_F_OPEN_END_TIMESTAMP: 6.782347
total_STDIO_F_CLOSE_END_TIMESTAMP: 6.856372
total_STDIO_F_WRITE_END_TIMESTAMP: 346.306913
total_STDIO_F_READ_END_TIMESTAMP: 6.856351
total_STDIO_F_FASTEST_RANK_TIME: 0.000000
total_STDIO_F_SLOWEST_RANK_TIME: 0.000000
total_STDIO_F_VARIANCE_RANK_TIME: 0.000000
total_STDIO_F_VARIANCE_RANK_BYTES: 0.000000

我正在 grep 使用 grep -Ein 'total_stdio_read|total_posix_write|total_stdio_write|total_posix_read' $file | cut -d ':' -f 3 | column -x >> $temp

期望的输出是:

2           0           0           184
2           0           0           184
765311      61423       6454323302  470948
598500      678403      6454288800  1810469

使用 BASH 'printf' 内置函数。这与 C printf() 具有相同的格式化语法,因此有很多选项。

示例:

$ printf "%-20s %3f\n" abc 3.4
abc                  3.400000

我假设您需要每列 10 个字符的长度加上 2 个字符的额外间距。 如果数据不适合列(数据未被截断),请增加长度。

xargsprintf:

$ <your commands> | xargs -n4 printf '%-10s  %-10s  %-10s  %-10s\n'
2           0           0           184
2           0           0           184
765311      61423       6454323302  470948
598500      678403      6454288800  1810469

awkprintf:

$ <your commands> | awk '{for(i=1;i<=NF;i++) printf "%-10s%s", $i, (i==NF ? ORS : "  ")}'
2           0           0           184
2           0           0           184
765311      61423       6454323302  470948
598500      678403      6454288800  1810469

或者干脆 column -t:

$ <your commands> | column -t
2       0       0           184
2       0       0           184
765311  61423   6454323302  470948
598500  678403  6454288800  1810469

所以对我有用的是混合解决方案。

<command output> | cut -d ' ' -f 2 | column -x | xargs -n4 printf '%-10d %-10d %-10d %-10d\n'