# first read and numericaly sort the lines my @lines = sort {$a <=> $b} <>; # then loop over data on STDIN # and write it to STDOUT my $line = shift @lines; while (<>){ if ($.==$line){ s/foo/bar/g; $line = shift @lines; } print; }