How to align a column in a text file

text processing

Using bash on Linux, how can I process a text file such that space is inserted before a certain column so that column is aligned in the output? For example:

Input

1653455 ASDFASDF22 bla bla bla asd xmv ASDFASDF22 AA
1944444 ASDFASDF22 klasdfmxvl yxklc erisa ask xdk asdm ase ASDFASDF22 BB
1984945 ASDFASDF22 jklyck aklsdfl asfjasl asdkkcii wdkkkxd aslasl wqe ASDFASDF22 BB

Output

1653455 ASDFASDF22 bla bla bla asd xmv                                ASDFASDF22 AA
1944444 ASDFASDF22 klasdfmxvl yxklc erisa ask xdk asdm ase            ASDFASDF22 BB
1984945 ASDFASDF22 jklyck aklsdfl asfjasl asdkkcii wdkkkxd aslasl wqe ASDFASDF22 BB

The columns between the two ASDFASDF22s must be less than 50 characters, or it should be truncated.

Best Answer

One solution using perl:

Content of script.pl:

use warnings;
use strict;

## Acept one argumnet, the input file.
@ARGV == 1 or die qq[Usage: perl $0 input-file\n];

while ( <> ) {
        ## Remove last '\n' char.
        chomp;

        ## Split line with string 'ASDFASDF22'
        my @f = split /(ASDFASDF22)/;

        ## Print line but print first 49 chars plus a space of the special string.
        printf qq[%s%-50s%s\n],
                join( qq[], @f[0,1] ),
                substr( $f[2], 0, 49 ) . qq[ ],
                join( qq[], @f[3..$#f] );
}

Execute the script:

perl script.pl infile

And output:

1653455 ASDFASDF22 bla bla bla asd xmv                              ASDFASDF22 AA
1944444 ASDFASDF22 klasdfmxvl yxklc erisa ask xdk asdm ase          ASDFASDF22 BB
1984945 ASDFASDF22 jklyck aklsdfl asfjasl asdkkcii wdkkkxd aslasl w ASDFASDF22 BB
Related Question