Chad Kellerman wrote:
>
> Hey guys,
Hello,
> I know you can do one a liner that appends a string after line in a
> file:
> ie: perl -p -i -e 's/$oldsting/$1\n$nextline/' file.txt
You don't assign any values to $oldsting, $nextline or $1 so that will
not do much.
> But I was doing it in a script:
You can see how Perl sees that command line program by using the
B::Deparse module.
$ perl -MO=Deparse -p -i -e 's/$oldsting/$1\n$nextline/' file.txt
LINE: while (defined($_ = <ARGV>)) {
s/$oldsting/$1\n$nextline/;
}
continue {
print $_;
}
-e syntax OK
Which can be simplified to:
while ( <> ) {
s/$oldsting/$1\n$nextline/;
print;
}
> #!/usr/bin/perl
> use strict;
> my $conf = "/home/bob/my.cnf";
> my $string = "mysqld]";
> my $replace = "bob was here";
>
> open (FILE, "$conf") or die "can not open $conf: $!\n";
> my @file = <FILE>;
> close (FILE);
> for (my $line = 0; $line <= $#file; $line++)
> {
> $/ = '[';
You are setting the Input Record Separator but it is too late as you
have already finished reading the file.
> if ($file[$line] =~ /$string$/)
> {
> $file[$line] .= "$replace";
> last;
> }
> }
> open (FILE, ">$conf") or die "can not open $conf: $!\n";
> print FILE @file;
> close (FILE);
>
> Then I was thinking, there has got to be a better way of doing this..
Since you have "last;" in the loop I am assuming that you only want to
modify the first occurrence of $string in the file.
#!/usr/bin/perl
use warnings;
use strict;
$/ = '[';
$^I = '.bak';
@ARGV = '/home/bob/my.cnf';
my $string = 'mysqld]';
my $replace = 'bob was here';
while ( <> ) {
chomp;
?\A$string\s+\z? and s/($string)/$1\n$replace/;
print "$_$/";
}
__END__
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]