10

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
  • 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? – user34720 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
  • 2
    No, don't post images of text. I was just going to copy and paste that text to be able to help you, and now I can't. – Kusalananda Jan 16 '17 at 11:43
  • 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
16

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.