in reply to Replacing Text At Specific Positions

Working, tested code:

use strict; use warnings; my $usage_message = "usage: $0 input_file output_file\n"; die $usage_message if @ARGV != 2; my ( $input_file, $output_file ) = @ARGV; open my $in_fh, '<', $input_file or die "Could not open input file 1 '$input_file': $!"; open my $out_fh, '>', $output_file or die "Could not open output file '$output_file': $!"; while ( my $line = <$in_fh> ) { chomp $line; warn unless length($line) == 210; if ( $line =~ m/^2/ ) { # Do Nothing! # A line starting with a '2' is a # header and is left unchanged. } else { # Change postions 100 and 149 substr( $line, 100-1, 1, '9' ); substr( $line, 149-1, 1, 'Z' ); } print {$out_fh} $line, "\n"; } close $in_fh or warn "Could not close input file 1 '$input_file': $!"; close $out_fh or warn "Could not close output file '$output_file': $!";
Or use this one-liner:
perl -wlpe 'if(!/^2/){substr($_,99,1,"9");substr($_,148,1,"Z");}' <in. +dat >out.dat

Replies are listed 'Best First'.
Re^2: Replacing Text At Specific Positions
by sheasbys (Initiate) on Jun 05, 2007 at 16:53 UTC
    Util,

    Thanks so much for the code. As a Newbie this has taught me a lot and I am astounded at the concise code to accomplish what originally started with 100 lines or so on my first convoluted attempt and now it can be distilled into one line.

    Thanks to you and to the other contributers,

    Stephen