http://www.perlmonks.org?node_id=1024002

MVRS has asked for the wisdom of the Perl Monks concerning the following question:

This node falls below the community's threshold of quality. You may see it by logging in.

Replies are listed 'Best First'.
Re: Rearranging columns in multiple text files
by marto (Cardinal) on Mar 18, 2013 at 10:25 UTC
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Rearranging columns in multiple text files
by igelkott (Priest) on Mar 18, 2013 at 11:27 UTC

    Nothing wrong with cut or calling unix commands in general but may as well use the normal Perl commands once you've started. In particular, look into split so for each file you could do something like:

    @a = split(/\t/); print "$a[0]\t$a[1]\t$a[12]\t$a[11]\n";
    There are fancier ways to do this but seems like it'd be best to keep it simple to begin with. The other parts depend on whether you are writing all results to a single file or operating on each file individually, etc.

Re: Rearranging columns in multiple text files
by reisinge (Hermit) on Mar 18, 2013 at 13:32 UTC

    Hi, let's suppose we have tab-separated data like that in the lines after the __DATA__ token and we want to swap columns two and three:

    use strict; use warnings; while (<DATA>) { # go through data line by line chomp; # don't forget to remove newline character my @fields = split /\t+/; print join "\t", # join fields with tab @fields[ 0, 2, 1 ], # select fields using array slice "\n"; } __DATA__ Col1 Col2 Col3 a b c 1 2 3

    To work with files, just

    • add $^I = ".bak"; before the while loop to edit files in place keeping backups
    • replace <DATA> with <> (diamond operator)

    and then run the program like this:

    $ perl script.pl *.dat

    Excellence is an art won by training and habituation: we do not act rightly because we have virtue or excellence, but we rather have these because we have acted rightly. -- Will Durant