bash 如何使用 paste(1) 排列列?或者如何在外壳中制作对齐的表格合并线?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2968219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:09:53  来源:igfitidea点击:

How to line up columns using paste(1)? or how to make an aligned table merging lines in the shell?

linuxbashunixscriptingshell

提问by snap

I want to merge lines such that the merged lines are aligned on the same boundary. UNIX paste(1) does this nicely when lines all meet at the same tab boundary, but when lines differ in size (in the file that lines are being merged into), the text comes out awkward.

我想合并线条,使合并的线条在同一边界上对齐。当所有行都在同一个制表符边界处相遇时,UNIX paste(1) 可以很好地做到这一点,但是当行的大小不同(在行被合并到的文件中)时,文本会显得笨拙。

Example of paste(1) that has the desired effect:

具有所需效果的 paste(1) 示例:

$ echo -e "a\nb\nccc\nd" | paste - -
a       b
ccc     d

Example of paste(1) with undesired effect:

具有不良效果的 paste(1) 示例:

$ echo -e "a\nb\ncccccccccccc\nd" | paste - -
a       b
cccccccccccc    d

Note how the 2nd column doesn't line up. I want 'b' to line up with 'd', which requires an additional tab. Unfortunately I believe this is the limit for the paste utility, so if anyone has any idea of how to get the desired effect above, I'd love to hear it.

请注意第二列如何不对齐。我希望 'b' 与 'd' 对齐,这需要一个额外的选项卡。不幸的是,我相信这是粘贴实用程序的限制,所以如果有人知道如何获得上述所需的效果,我很想听听。

回答by Robert Wohlfarth

Check out the columnutility...

查看实用程序...

$ echo -e "a\nb\ncccccccccccc\nd" | paste - - | column -t
a             b
cccccccccccc  d

回答by mattgately

See the answer herefor a easy way to handle this when the lines may have spaces or other characters already using the prcommand. For example:

当行可能有空格或其他字符已经在使用该命令时,请参阅此处的答案以获取一种简单的方法来处理此问题pr。例如:

pr -m -t -w 200 file1 file2

回答by Michael Aaron Safyan

You can use the printf utilityto create formatted output, using the same format specifiers as printf. With the format specifiers, you can specify a minimum field width. For example:

您可以使用printf 实用程序创建格式化输出,使用与printf相同的格式说明符。使用格式说明符,您可以指定最小字段宽度。例如:

printf "%30s%30s\n" "Alpha" "Bravo"