learingperl01
MIS
I am trying to write a script to edit a file when matched it will replace the line with the new static entry. I am a bit stuck and wondering if someone could please help me!!
For example I want an entire line to be removed if a match is found anywhere on that line using a regex of .*[0-9]{4}.*
test line with no number
this is a test line
this is a test line 5677
this is a test line 2334
this is a test line 1235 this is a test line
The problem with my code is that the lines that don't match also get removed. What I am trying to do is have the script add the lines that don't match into the new file without modifying them as well up appending the lines that match. Right now the script is only adding/appending the lines that match the regex and not doing anything with the ones that don't. Output shown below
this worked
this worked
this worked
Any ideas help? I would really appreciate it.
open(FILE,$ARGV[0]);
@array1 = <FILE>;
open(NEWFILE,">/home/testuser01/testfile.txt");
foreach $line(@array1)
{
chomp $line;
if($line =~ /id\:745[0-9]{4}/)
{
$line =~ s/.*id\:745[0-9]{4}.*/this worked/sgi;
print NEWFILE $line, "\n";
}
else
{
print NEWFILE "$_" , "\n";
print $_;
}
}
close($FILE);
close($NEWFILE);
For example I want an entire line to be removed if a match is found anywhere on that line using a regex of .*[0-9]{4}.*
test line with no number
this is a test line
this is a test line 5677
this is a test line 2334
this is a test line 1235 this is a test line
The problem with my code is that the lines that don't match also get removed. What I am trying to do is have the script add the lines that don't match into the new file without modifying them as well up appending the lines that match. Right now the script is only adding/appending the lines that match the regex and not doing anything with the ones that don't. Output shown below
this worked
this worked
this worked
Any ideas help? I would really appreciate it.
open(FILE,$ARGV[0]);
@array1 = <FILE>;
open(NEWFILE,">/home/testuser01/testfile.txt");
foreach $line(@array1)
{
chomp $line;
if($line =~ /id\:745[0-9]{4}/)
{
$line =~ s/.*id\:745[0-9]{4}.*/this worked/sgi;
print NEWFILE $line, "\n";
}
else
{
print NEWFILE "$_" , "\n";
print $_;
}
}
close($FILE);
close($NEWFILE);