Shell – Formatting text into columns

columnsshelltext formatting

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

Best Answer

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
Related Question