Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and replace a particular string in a file using Perl [duplicate]

Tags:

Possible Duplicate:
How to replace a string in an existing file in Perl?

I need to create a subroutine that does a search and replace in file.

Here's the contents of myfiletemplate.txt:

CATEGORY1=youknow_<PREF>  
CATEGORY2=your/<PREF>/goes/here/

Here's my replacement string: ABCD

I need to replace all instances of <PREF> to ABCD

like image 944
cr8ivecodesmith Avatar asked Nov 22 '11 09:11

cr8ivecodesmith


2 Answers

A one liner:

perl -pi.back -e 's/<PREF>/ABCD/g;' inputfile
like image 82
Toto Avatar answered Oct 07 '22 19:10

Toto


Quick and dirty:

#!/usr/bin/perl -w

use strict;

open(FILE, "</tmp/yourfile.txt") || die "File not found";
my @lines = <FILE>;
close(FILE);

foreach(@lines) {
   $_ =~ s/<PREF>/ABCD/g;
}

open(FILE, ">/tmp/yourfile.txt") || die "File not found";
print FILE @lines;
close(FILE);

Perhaps it i a good idea not to write the result back to your original file; instead write it to a copy and check the result first.

like image 32
Erik Avatar answered Oct 07 '22 19:10

Erik