Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

bash - Replace tab with variable amount of spaces, maintaining the alignment

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?

question from:https://stackoverflow.com/questions/66050075/replace-tab-with-variable-amount-of-spaces-maintaining-the-alignment

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ^Is:

$ 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$

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...