3

How do I right justify the columns of a file in awk, sed, or bash ?

My file is currently left justified and space delimited.

Can I used printf or rev?

Here is what my file looks like :

$ cat file
14,107     aaa  12,436  0.0  0  0  313  0  373
3,806,201  bbb  1,573   0.0  0  0  -25  0  -25

And using rev doesn't give me the output I'm looking for.

$rev file  | column -t | rev
14,107  aaa  12,436  0.0  0  0  313  0  373
3,806,201  bbb   1,573  0.0  0  0  -25  0  -25
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
user196711
  • 311
  • 5
  • 17
  • If `rev` doesn't work for your data I would use python to format it however I don't think you example is representative of your actual problem and I don't want to play the revision game. – Chris Seymour Aug 02 '13 at 18:13
  • Why don't you also show our expected output. – anubhava Aug 03 '13 at 06:44
  • 4
    `rev` wouldn't work if items in the first column have different lengths. Padding a column and later stripping it away would work: `rev file|sed 's/$/ ./'|column -t|rev|sed 's/^...//'`. By the way, I don't think it is a duplicate. – jxy Nov 30 '16 at 17:21
  • 1
    I have a good answer I'd like to post. This is not a duplicate. The linked question is about columns of a *fixed width*. In this question we have columns of variable width. – Socowi Jan 18 '19 at 12:28

1 Answers1

12

In lieu of a specific example here is a general solution using a trick with rev:

$ cat file
a 10000.00 x
b 100 y
c 1 zzzZZ

$ rev file | column -t | rev
a  10000.00      x
b       100      y
c         1  zzzZZ

Where column -t is replaced by whatever you are trying to do.

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
  • 2
    +1. note that this will right-justify every column. – glenn jackman Aug 02 '13 at 17:44
  • @glennjackman right, it sounds like that is what the OP is asking for. I have changed the example so the behaviour is better shown. – Chris Seymour Aug 02 '13 at 17:47
  • 3
    Will not work properly if the leftmost columns aren't all the same width, but clever nonetheless – rix0rrr Jan 25 '18 at 15:05
  • 3
    To work around the requirement *»entries in the leftmost column must be of equal width«* you can insert a dummy column and remove it later: `sed 's/^/a\t/' file | rev | column -t | rev | cut -c3-`. – Socowi Jan 22 '19 at 14:11