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

I need to insert a space (or any other delimiter for that matter) at the 25th column in a large text file. I have seen lots of ways of splitting a file on a delimiter, but I need to insert one at a consistent point. So how do I globally insert a space at a column in a file. Any assistance gratefully received. Thanks Rich

Replies are listed 'Best First'.
Re: How to split a document at a column
by davorg (Chancellor) on Mar 29, 2007 at 11:41 UTC

      Two bugs:

      • You'll die with an substr outside of string message if there are any blank or short lines.
      • You'll add the space after the newline if line is one character less than the insert point.

      Fix:

      while (<>) { chomp; substr($_, 24, 0, ' ') if length() > 24; print("$_\n"); }
      perl -i~ -ple "substr($_, 24, 0, ' ') if length() > 24" file

      Tested.

Re: How to split a document at a column
by planetscape (Chancellor) on Mar 29, 2007 at 14:20 UTC
Re: How to split a document at a column
by salva (Canon) on Mar 29, 2007 at 11:43 UTC
    you can use substr for that:
    perl -i.bak -ple 'substr($_, 25, 0, " ") if length > 24' filename.txt
      I find it odd that you add a space at the end of "1234567890123456789012345", but you don't add any spaces at the end of "123456789012345678901234".
Re: How to split a document at a column
by Ojosh!ro (Beadle) on Mar 29, 2007 at 13:04 UTC

    Isn't this something you can easily do with a regex?
    Something along the lines of:

    my $text = ''; # put your complete works of Willie here my $separator = '|'; # and your separator here $text =~ s/[\^\n]([^\$\n]{25})/$1$separator/sg; print $text;

    if( exists $aeons{strange} ){ die $death unless ( $death%2 ) }