-1

I have a file with below strings in it which are misaligned. I want to align this file properly so that each of the word in each line are properly spaced.

3 281 901.188.30.53 901001 1 poihelloswqs-1146414
3 598 901.189.166.233 901001 1 poihelloswqs-90877846
3 300 901.156.77.57 901001 1 poihelloswqs-90137229
3 263 901.156.17.80 901001 1 poihelloswqs-90135797
3 264 901.875.875.79 901001 1 poihelloswqs-1389375
3 265 901.189.153.234 901001 1 poihelloswqs-1568332
3 266 901.218.93.873 901001 1 poihelloswqs-3240561
3 268 901.158.76.23 901001 1 poihelloswqs-3242066
3 269 901.218.30.120 901001 1 poihelloswqs-3242532

It should output something like this: This way they all are properly aligned. Is this possible to do in Linux?

3 281 901.188.30.53     901001 1 poihelloswqs-1146414
3 598 901.189.166.233   901001 1 poihelloswqs-90877846
3 300 901.156.77.57     901001 1 poihelloswqs-90137229
3 263 901.156.17.80     901001 1 poihelloswqs-90135797
3 264 901.875.875.79    901001 1 poihelloswqs-1389375
3 265 901.189.153.234   901001 1 poihelloswqs-1568332
3 266 901.218.93.873    901001 1 poihelloswqs-3240561
3 268 901.158.76.23     901001 1 poihelloswqs-3242066
3 269 901.218.30.120    901001 1 poihelloswqs-3242532
flash
  • 1,455
  • 11
  • 61
  • 132
  • Use `printf()` with fixed width fields. – Barmar Sep 24 '19 at 19:12
  • 1
    Also see [Why is the “how to move the turtle in logo” question closed?](https://meta.stackexchange.com/q/158289) and [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – jww Sep 24 '19 at 19:14
  • `column -t` is meant for this. it has switches to specify input separator, output separator, right-align certain columns, etc. – hIpPy Sep 10 '22 at 21:36

1 Answers1

0

It's very ugly but this may work:

cat xx | ruby -nle 'puts $_.split().join("\t")' |pr --expand-tabs -tT

You may need to replace the single \t with multiple tab characters if your columns vary greatly in width.

This is ruby splitting the line on any white space, then joining using tabs. Finally pr is replacing tabs with spaces (and the -tT avoids the annoying headers and pagination)

If you know the fields are separated by a single character tr can do the replacement easily:

 cat xx | tr ' ' "\t"  |pr --expand-tabs -tT
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
nimrodm
  • 23,081
  • 7
  • 58
  • 59
  • or with GNU sed `sed 's/ /\t/3' file` or `sed 's/ /\t/3' file | column -s $'\t' -t` – Cyrus Sep 24 '19 at 19:21
  • If I execute this `cat align.txt | ruby -nle 'puts $_.split().join("\t")' |pr --expand-tabs -tT|` command, then it gives me this line `>`. Below is the output I got: `host:~$ cat align.txt | ruby -nle 'puts $_.split().join("\t")' |pr --expand-tabs -tT| >` – flash Sep 24 '19 at 19:22
  • @Cyrus I got a seg fault with your second command on my file. Not sure why? – flash Sep 24 '19 at 19:24
  • @flash: Maybe a bug in the implementation of the `column` command you are using. – Cyrus Sep 24 '19 at 19:28