954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to find and replace strings in a file?

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

---code --
#!/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 = ;

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

Paryushan
Newbie Poster
9 posts since Dec 2008
Reputation Points: 10
Solved Threads: 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

KevinADC
Posting Shark
921 posts since Mar 2006
Reputation Points: 246
Solved Threads: 67
 

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

Paryushan
Newbie Poster
9 posts since Dec 2008
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You