in reply to Re^3: substitute on file line by line not working syntax error
in thread Search and Replace line by line not working on Filehandle

Ah ok. Thanks. Thats one fault (recycled old code without thinking first). But it prints a line **after** the line that should be changed, i want to **overwrite** the line not "append". Any idea? Something like moving the "Write Pointer" back 1 line and write it there?


Thanks
MH
  • Comment on Re^4: substitute on file line by line not working syntax error

Replies are listed 'Best First'.
Re^5: substitute on file line by line not working syntax error
by cdarke (Prior) on Jan 15, 2010 at 10:52 UTC
    Sure you can, BUT the new record (line) must be exactly the same length as the old one. For example, if you just want to comment out a line by placing a '#' at the front then you cannot overwrite the existing line since that would be one extra character - you would overwrite the first character of the next line in the file.

    Here is a simple example where the new line is the same length as the old:
    use warnings; use strict; use Fcntl qw(SEEK_CUR); # open existing file for read/write open (my $in, '+<', 'file1.txt') || die "Unable to open file1.txt:$!"; while (<$in>) { # Identify the record if (/4444/) { # Construct the new record s/4/#/g; # Position the file pointer seek ($in, -length($_)-1, SEEK_CUR); print $in $_; } } close $in;
    Input file was:
    111111111111111 22222222 33333333333 4444444 5555555555555555 66666666666
    file after processing is:
    111111111111111 22222222 33333333333 ####### 555555555555555 66666666666

      OK. Seems i have to use the "Seek thing". This seems to work:

      #!/usr/bin/perl use strict; use warnings; open (IN, "+<C:/oracle/ora81/network/ADMIN/SQLNET.ORA") || die "cant o +pen $!"; my @file = <IN>; seek IN,0,0; foreach my $file (@file){ $file =~ s/^SQLNET\.AUTHENTICATION_SERVICES=\ \(NTS\)$/#\ SQLNET\.AUTH +ENTICATION_SERVICES=\ \(NTS\)/i; print IN $file; } close IN;

      Thanks
      MH
        I'm surprised it works - are you sure?
        seek IN,0,0; just sets the position to beginning of file. See seek.