如何清理文本中未对齐的列? [英] How can I clean up misaligned columns in text?

查看:28
本文介绍了如何清理文本中未对齐的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 C 程序,它输出两列,完全未对齐.未对齐的原因是第一列中的单词长度非常不同.

I have a C program that outputs two columns, utterly misaligned. The reason for the misalignment is lengths of words in the first column are very different.

我在 vi 中打开了一个输出文件.如何快速对齐这两列?我可以使用 awk、perl、sed,而不仅仅是 vi (7.2) 工具集.另外,对于多于两列的文件,我们可以有一个通用的解决方案吗?

I have an output file opened in vi. How do I quickly align these two columns? I am fine with using awk, perl, sed, and not just vi (7.2) toolset. Also, can we have a generic solution for files with more than two columns?

这里是示例文件

column1               column2
-------               -------
sdfsdfsddfsdfsdfsdfsd         343r5
dfgdfgdf             234
gdfgdfgdfgdfgf            645

推荐答案

想必您首先使用 printf 来输出列.您可以在格式字符串中使用额外的修饰符以确保对齐.

Presumably you are using printf to output the columns in the first place. You can use extra modifiers in your format string to make sure things get aligned.

  • 要打印特定宽度的列(右对齐),请在格式标志之前添加宽度,例如,%10s"将打印宽度为 10 的列.如果您的字符串长度超过 10 个字符,则列会比你想要的长,所以选择一个最大值.如果字符串较短,则会用空格填充.
  • 要左对齐一列,请在前面放置一个 - 符号,例如%-10s".我个人喜欢左对齐字符串和右对齐数字.
  • 如果您要打印地址,您可以将填充字符从空格更改为带有前导零的零:%010x".

举一个更深入的例子:

printf("%-30s %8s %8s\n", "Name", "Address", "Size");
for (i = 0; i < length; ++i) {
    printf("%-30s %08x %8d\n", names[i], addresses[i], sizes[i]);

这将打印三列,如下所示:

This would print three columns like this:

Name                            Address     Size
foo                            01234567      346
bar                            9abcdef0     1024
something-with-a-longer-name   0000abcd     2048

这篇关于如何清理文本中未对齐的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆