Gossamer Forum
Home : General : Perl Programming :

search and replace a string in text file.

Quote Reply
search and replace a string in text file.
I have a very simple question .... I have a text file and have to replace only one field in the string.


I have to first match the first field ID (e.g. 125) and then replace the 'Read' with 'Unread' only for this line in the text file and save it.
any ideas as how to do it. I have tried a couple of methods but I am stuck with it.

Search and Replace (i.e. Regex) is not the question here, I am asking for how to re-write the file once the replacement has been made.

thanks in advance.

Last edited by:

zeshan: Feb 27, 2004, 1:17 PM
Quote Reply
Re: [zeshan] search and replace a string in text file. In reply to
Try this;


use strict;

my $id_to_match = '125';

unlink('file_new.txt'); # get rid of the new version...

open(READIT,"file.txt") || die "Cant read file.txt. Reason: $!";
open(WRITEIT,">>file_new.txt") || die "Cant write file_new.txt. Reason: $!";
while (<READIT>) {

if ($_ =~ /^$id_to_match\|/) {
$_ =~ s/Read/Unread/;

print WRITEIT $_; # may need to change to "$_ \n"


# now the new version should saved to file_new.txt

Hope that helps.


Andy (mod)
Want to give me something back for my help? Please see my Amazon Wish List
GLinks ULTRA Package | GLinks ULTRA Package PRO
Links SQL Plugins | Website Design and SEO | UltraNerds | ULTRAGLobals Plugin | Pre-Made Template Sets | FREE GLinks Plugins!