在Linux中将分隔文件转换为固定宽度

时间:2015-01-07 18:44:11

标签: linux bash

使用可用于bash的工具,如何转换分隔数据

foo|bbbaaarrr|bazz

到固定宽度数据

foo      bbbaaarrrbazz     EOL   

我尝试使用列,因为文档暗示我可以定义列宽,但没有用。 我确定使用sed或awk这是微不足道的,但我不熟悉它们。

1 个答案:

答案 0 :(得分:11)

以下内容对您有用:

column -t -s '|' input_file_here

它会将输入文件转换为表格格式。输入记录分隔符由-s指定。如果您想在字段中使用空格填充以外的其他内容,请使用-o设置输出分隔符。输出分隔符默认为两个空格,因此输出中每列之间将有两个空格。

示例:

$ cat input
hello|world|testing
a|b|c
another|test|line

$ column -t -s '|' input
hello    world  testing
a        b      c
another  test   line

http://man7.org/linux/man-pages/man1/column.1.html


编辑:

如果您需要每个字段都是固定长度,则可以使用awk。您需要为文件设置输入分隔符,但是这样的事情应该有效:

$ awk -F '|' '{ for (i=1; i<=NF; i++) { printf("%-10s", $i); } print ""; }' input
hello     world     testing
a         b         c
another   test      line

只需更改printf语句中指定的字段宽度。