Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clean up misaligned columns in text?

Tags:

text

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.

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?

Here is sample file

column1               column2 -------               ------- sdfsdfsddfsdfsdfsdfsd         343r5 dfgdfgdf             234 gdfgdfgdfgdfgf            645 
like image 814
vehomzzz Avatar asked Oct 01 '09 17:10

vehomzzz


People also ask

How do you align columns?

On the Home tab, click Paragraph, and then click Align. Select the Align with option and then select the paragraph tag pertaining to the column one paragraph. Click OK.

How do you make a column in printf?

Each column is color-coded so you can see that column one is 7 characters wide, column two is 11 characters wide, and column three is 10 characters wide. The code to generate this would look like: printf("Column1 Column2 Column3\n"); printf("%7d%11d%10d\n", 100, 1221, 9348);


1 Answers

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.

  • To print a column of a specific width (right-justified), add the width before the formatting flag, e.g., "%10s" will print a column of width 10. If your string is longer than 10 characters, the column will be longer than you want, so choose a maximum value. If the string is shorter, it will be padded with spaces.
  • To left-justify a column, put a - sign in front, e.g., "%-10s". I like to left-justify strings and right-justify numbers, personally.
  • If you are printing addresses, you can change the fill characters from spaces to zeroes with a leading zero: "%010x".

To give a more in depth example:

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 
like image 125
Jay Conrod Avatar answered Oct 02 '22 13:10

Jay Conrod