http://qs321.pair.com?node_id=652566


in reply to Newbie: uses/limits of perl in editing files

Welcome to the monastery. From the task description I'd say perl is very well suited. I'll give you an example for a program that roughly does what you describe

#!/usr/bin/perl use warnings; use strict; my $filename = "whateveryourfileiscalled.txt"; my $newfile = "whateveryouwantthechangedfiletobecalled.txt"; open (my $rfh,"<",$filename) or die "Can't open file $filename : $!"; open (my $wfh,">",$newfile) or die "Can't open file $newfile : $!"; while (my $line = <$rfh>) { if ($line =~ m/^HEADER/) { chomp $line; my $number = 42; # change to whatever number you want to use $line .= $number."\n"; } if ($line =~ m/^REMARK/) { print {$wfh} "Extra line\n" # Change to whatever extra line yo +u want } print {$wfh} $line; } close $rfh or die "Can't close $filename : $!"; close $wfh or die "Can't close $newfile : $!";
Or you could do this in a perl oneliner (which will change the original file):
perl -pi -e 'chomp;s/^(HEADER.*)$/${1}42/;s/^(REMARK.*)$/Extra line\n$ +1/;$_.="\n"' whateveryourfileiscalled.txt
Caveat: Both of these are for systems where the line ending is "\n" (i.e. not Windows), adjust appropriately for other OSes. Update: the caveat is not actually correct, as pointed out by naikonta and wfsp, except possibly for the case outlined by Sixtease, also fixed in his update. Thanks to all of you.

All dogma is stupid.