Search code examples
pythonperlfileoctavefile-manipulation

Use Perl to manipulate file from within Octave


I have a need to manipulate a file from within Octave in the middle of a routine. At the moment I end this routine by saving a file from Octave with

save data_for_training -ascii train_data

and then manually, and tediously, edit the saved file and then resume operations in a new and different Octave routine by first reading the edited file. Conceptually the file manipulations required are the reverse of those outlined in this SO posting, namely a saved file that looks like this

a b c d e f ... z 0 0 0 0 1  
g h i j k l ... z 0 0 0 1 0

has to be manipulated to

a b c d e f ... z  
0 0 0 0 1  
g h i j k l ... z  
0 0 0 1 0

where the letters are actually numbers, but I have used letters for clarity. The line breaks will always be before the fifth to last number on each line i.e. the last 0 0 0 0 1 on each line will need to be moved below the line and all numbers on all lines are space separated.

I have tagged this question with the Perl and Python tags as there are Perl and Python functions in Octave and so I assume that I can easily achieve what I want by writing a scriptfile to do the above manipulations. If I am correct in this assumption can anyone give me a start/weblink for the Perl/Python scriptfiles - I have never used either before?


Solution

  • #!/usr/bin/env perl
    while (<>) {
       my @f = split;
       print("@f[0..$#f-5]\n@f[-5..-1]\n");
    }
    

    or

    #!/usr/bin/env perl
    while (<>) {
       s/\S\K\s+(?=\S+(?:\s+\S+){4}$)/\n/;
       print;
    }
    

    Usage:

    perl script.pl file.in >file.out
    

    or

    script.pl file.in >file.out   # Requires: chmod u+x script.pl
    

    or

    perl -pale'$_="@F[0..$#F-5]\n@F[-5..-1]"' file.in >file.out
    

    or

    perl -pe's/\S\K\s+(?=\S+(?:\s+\S+){4}$)/\n/' file.in >file.out