0

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 $_;
}

Edited by mike_2000_17: Fixed formatting

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by Paryushan
0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.