Hi,

I am trying to find and replace a particular string in a file and save that file.

Here is what I did, where I am writing the output after replacement into new file.

I was trying to avoid to open the file for writing and try to use just s/// to do replacement in the same file. But its not working.

Any help would be appreciated.

Thanks

#!/usr/bin/perl
use strict;
use warnings;

open INPUT, "abc.txt" or die "Cannot open ldif file for reading : $!";
open OUTPUT, ">Newabc.txt" or die "Cannot open ldif file for writing : $!";

my $pattern = "old";
my $new = "new";

my @file = <INPUT>;

foreach (@file) {
        $_ =~ s/\b$pattern\b/$new/g;        
        print OUTPUT $_;
}

It looks like it should work but it will not alter the original file if thats what you are thinking. The only reason it will not work is if the regular expression is not finding the search pattern: \b$pattern\b

When posting a question, saying "it does not work" is next to useless. You have to describe what happens when you run the code and post any error messages your code might return.

To search and replace in the same file here is a snippet you can look over:

http://www.tek-tips.com/faqs.cfm?fid=6559

Thanks... I will follow the suggestions...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.