18

I have a file with two columns as shown below(example):

FILE 1:

John 1
Peter 2
Michael Rod 3
Su 7
Louise 9

I need to format this and my expected output should be:

FILE 1:

John        1
Peter       2
Michael Rod 3
Su          7
Louise      9
Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227
Ram
  • 335
  • 1
  • 2
  • 4
  • 1
    where are the 2 columns? – marc Jan 16 '17 at 11:31
  • Both outputs seems to be the same. Could you please give more details on your question? –  Jan 16 '17 at 11:32
  • 2
    How are columns defined? Is there a tab or some other character between the name and the number? How can we know that `Michael Rod 3` is 2 columns and not 3? – terdon Jan 16 '17 at 11:34
  • 1
    ditto what mmmint and terdon said; can you specify, for example, that it's the *last* column that needs to be indented over to allow for the width of the longest line? – Jeff Schaller Jan 16 '17 at 13:04

1 Answers1

22

If the input had been only two columns, I would have suggested to use column -t. This doesn't quite work here though since the column utility will treat any number of spaces or tabs as column delimiters:

$ column -t file1
John     1      
Peter    2      
Michael  Rod  3 
Su       7      
Louise   9      

"Michael Rod" is two columns, so that single row has one column more than the other rows, which messes up the output.

We can work around this by inserting a tab character before the last column and then let column use (only) that as a delimiter:

$ awk '{ $NF = "\t" $NF; print }' file1 | column -t -s $'\t'
John          1
Peter         2
Michael Rod   3
Su            7
Louise        9

In Awk, NF is the number of fields (columns), and $NF is the data in the last field. The script I'm using simply modifies the data of the last field by prepending a tab character, before printing the complete line.

If your shell doesn't understand $'\t', then you could pick another character that is not part of the data:

awk '{ $NF = "@" $NF; print }' file1 | column -t -s '@'
John          1
Peter         2
Michael Rod   3
Su            7
Louise        9
Kusalananda
  • 320,670
  • 36
  • 633
  • 936