Dru has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

I'm trying to open a file and replace some exisiting lines with new text. I do not want to print everything to a new file, I just want to modify the exisiting file. I'm stuck at the moment on how to replace the matching line with the text or do I HAVE to create a new file?

I appreciate any assistance.
#!/usr/bin/perl -w use strict; my $ip = '192.168.1.4; my $txt = 'Removed ' . $ip . ' by Dru'; my $file = '/data/syslog/log.backup'; open (FILE, "+<$file") or die "Can't open $file: $!\n"; while (<FILE>){ if (/.*\b$ip\b.*/){ # I thought this would work, but it doesn't s/$_/$txt/; print FILE; } }
Thanks,
Dru

Replies are listed 'Best First'.
Re: Replacing Lines in a File
by dragonchild (Archbishop) on May 26, 2004 at 18:58 UTC
    perl -pi -e '$ip="192.168.1.4";$_="Removed $ip by Dru" if /\b$ip\b/' / +data/syslog/lob.backup

    Run that at your command prompt. (note the signature!)

    Update: Fixed quoting issues. (Thanks, Zaxo!)

    ------
    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

    I shouldn't have to say this, but any code, unless otherwise stated, is untested

      Mucho Gracias dragonchild, that's exactly what I wanted. Man, I gotta learn those one liners.
Re: Replacing Lines in a File
by Stevie-O (Friar) on May 26, 2004 at 19:52 UTC
    As punkish has said, there's no way to do it other than by rewriting the entire file after where you're modifying. However, there are things that can severely reduce the actual amount of stuff you have to code to accomplish that. For your specific example, the -lpe -i.bak oneliner is probably the easiest. Here's an example of something using Tie::File, which allows you to treat a file as an array of lines (change the array, change the file).
    tie @array, 'Tie::File', '/data/syslog/log.backup' or die "Damnit, Jim +, he's dead: $!"; s/$ip/$txt/ for @array;
    --Stevie-O
    $"=$,,$_=q>|\p4<6 8p<M/_|<('=> .q>.<4-KI<l|2$<6%s!<qn#F<>;$, .=pack'N*',"@{[unpack'C*',$_] }"for split/</;$_=$,,y[A-Z a-z] {}cd;print lc
Re: Replacing Lines in a File
by punkish (Priest) on May 26, 2004 at 19:17 UTC
    Follow what dragonchild has advised above. But also note... no matter which way you do it, you are opening a file, changing its contents, writing it out again to replace the existing file. If you have many different modifications to make, you could tie the entire file contents to a hash, and then as you make changes to the contents of the hash, it would make the changes to the file for you. But you can't just change the contents of a file without rewriting it out... if that is what you want then you need a database of some sort. The simplest would be DB_File.