Reputation: 8105
I have a tab separated file, consisting of 7 columns.
ABC 1437 1 0 71 15.7 174.4
DEF 0 0 0 1 45.9 45.9
GHIJ 2 3 0 9 1.1 1.6
What I need is to replace the tab character with variable amount of space characters in order ot maintain the column alignment. Note that, I do not want every tab to be replaced by 8 spaces. Instead, I want 5 spaces after row #1 column #1 (8 - length(ABC) = 5), 4 spaces after row #1 column #2 (8 - length(1437) = 4), etc.
Is there a linux tool to do it for me, or I should write it myself?
Upvotes: 2
Views: 1361
Reputation: 12347
Use column
, as suggested in the comment by anubhava, specifically using -t
and -s
options:
column -t -s $'\t' in_file
From the column manual:
-s, --separator separators
Specify the possible input item delimiters (default is
whitespace).
-t, --table
Determine the number of columns the input contains and
create a table. Columns are delimited with whitespace, by
default, or with the characters supplied using the
--output-separator option. Table output is useful for
pretty-printing.
Upvotes: 0
Reputation: 203189
The POSIX utility pr called as pr -e -t
does exactly what you want and AFAIK is present in every Unix installation.
$ cat file
ABC 1437 1 0 71 15.7 174.4
DEF 0 0 0 1 45.9 45.9
GHIJ 2 3 0 9 1.1 1.6
$ pr -e -t file
ABC 1437 1 0 71 15.7 174.4
DEF 0 0 0 1 45.9 45.9
GHIJ 2 3 0 9 1.1 1.6
and with the tabs visible as ^I
s:
$ cat -ET file
ABC^I1437^I1^I0^I71^I15.7^I174.4$
DEF^I0^I0^I0^I1^I45.9^I45.9$
GHIJ^I2^I3^I0^I9^I1.1^I1.6$
$ pr -e -t file | cat -ET
ABC 1437 1 0 71 15.7 174.4$
DEF 0 0 0 1 45.9 45.9$
GHIJ 2 3 0 9 1.1 1.6$
Upvotes: 5
Reputation: 67467
There is command pair dedicated for this task.
$ expand file
will do exactly what you want. The counterpart unexpand -a
to do the reverse. There are few other useful options in both.
Upvotes: 3