Find the answer to your Linux question:
Results 1 to 4 of 4
Hi everyone I'm trying to do a "search and replace" on a cgi-file. I'm looking to replace d1 with the variable $a . Here is my script. Code: my @contents; ...
  1. #1
    Linux User
    Join Date
    Jul 2007
    Location
    Greece
    Posts
    277

    search and replace doesn't work as expected (Perl)

    Hi everyone

    I'm trying to do a "search and replace" on a cgi-file.

    I'm looking to replace d1 with the variable $a. Here is my script.

    Code:
    my @contents;
    my ($fileread, $filewrite, $line);
    my $infile = '/var/www/cgi-bin/test';
    
    open ($fileread, $infile) || die ("Can't open: $infile $!");
    
          my (@contents) = (<$fileread>);
    
          close ($fileread);
    
    open ($filewrite, '>', $infile) || die ("Can't open: $infile $!");
    
    foreach $line (@contents)
           {
            $line=~ s/d1/$a/;
            print $filewrite $line;
           }
           close ($filewrite);
    The above will replace the first occurrence of d and 1 but not d1. It shouldn't do that, isn't it?

    Is there anything I'm doing wrong here, Any suggestions please?

  2. #2

  3. #3
    Linux User
    Join Date
    Jul 2007
    Location
    Greece
    Posts
    277
    Thanks for the reply ghostdog but
    Code:
    \$a
    replaced d1 with $a instead of what $a is equal to.

  4. #4
    Linux User
    Join Date
    Jul 2007
    Location
    Greece
    Posts
    277
    I just realised that the script above searches and replaces the first occurrence of d1 in each line. Do you know how I can prevent this from happening?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...