0

I have a file like this

AAA:111111:FIRSTLINE
BBBBBBB:22222222222:SECONDLINE
CCC:33333333333333333333:THIRD LINE

And I wanted to change each ":" by a tab. For that, I used the tr command

tr ":" "\t"

But I got this

ABC     12345   FIRSTLINE
DEFGH   1112232 SECONDLINE
IJK     77623786487261  THIRD LINE

I want to make the words in the third column all starting in the same place, but it seems that when a word in the previous column is too long, the word from the next column moves much foward than I want. Is there a quick way of solving this?

Thanks.

Andy Dalton
  • 13,654
  • 1
  • 25
  • 45
Mykas4ms
  • 3
  • 1
  • 1
    Does this answer your question? [Align columns in ASCII file](https://unix.stackexchange.com/questions/65370/align-columns-in-ascii-file) Attention to the second answer that explains how to use a custom delimiter, in your case, `:`. – Quasímodo Mar 14 '21 at 17:24
  • Another solution would be to use `expand` with specific tab settings. `cat file.txt | tr : '\t' | expand -t9,31` – Ken Jackson Mar 14 '21 at 17:58

2 Answers2

1

Try this:

$ cat ex
AAA:111111:FIRSTLINE
BBBBBBB:22222222222:SECONDLINE
CCC:33333333333333333333:THIRD LINE

$ column --table --separator ':' ex
AAA      111111                FIRSTLINE
BBBBBBB  22222222222           SECONDLINE
CCC      33333333333333333333  THIRD LINE

The column command generates a table with the given separator.

Andy Dalton
  • 13,654
  • 1
  • 25
  • 45
0

I don't know if tr can solve it, but awk is great at solving problems like that.

The printf command in awk works very similar to in C. The minus sign in the format string %-8s makes the output left-justified.

The switch -F: sets the field separator to :, which causes awk variabels $1, $2 and $3 to be set to the text separated by that separators. Be sure to use single quotes on the command line so bash doesn't try to interpret them.

awk -F: '{printf "%-8s %-21s %s\n",$1,$2,$3}' file.txt

With your input file, I got this output:

AAA      111111                FIRSTLINE
BBBBBBB  22222222222           SECONDLINE
CCC      33333333333333333333  THIRD LINE
Ken Jackson
  • 307
  • 1
  • 5
  • The fixed lengths will cut of strings that are too long. One would have to define with the longest strings in each column to exclude that. – FelixJN Mar 14 '21 at 19:09
  • This is a concept demonstration, @FelixJN. In some contexts the user knows his maximum field widths, so this would be perfect. Also, if columns automatically adjust to fit the data, one malformed line could cause the first or second column to be wider than the page, which would destroy the intent. – Ken Jackson Mar 14 '21 at 19:28