Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a string in an existing file in Perl

Tags:

regex

perl

I want to replace the word "blue" with "red" in all text files named as 1_classification.dat, 2_classification.dat and so on. I want to edit the same file so I tried the following code, but it does not work. Where am I going wrong?

@files = glob("*_classification.dat"); foreach my $file (@files) {     open(IN,$file) or die $!;     <IN>;     while(<IN>)     {         $_ = '~s/blue/red/g';         print IN $file;     }     close(IN) } 
like image 325
user831579 Avatar asked Aug 09 '11 10:08

user831579


People also ask

How do I replace a string in a Perl script?

Performing a regex search-and-replace is just as easy: $string =~ s/regex/replacement/g; I added a “g” after the last forward slash. The “g” stands for “global”, which tells Perl to replace all matches, and not just the first one.

What is in Perl regex?

Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“.


2 Answers

Use a one-liner:

$ perl -pi.bak -e 's/blue/red/g' *_classification.dat 

Explanation

  • -p processes, then prints <> line by line
  • -i activates in-place editing. Files are backed up using the .bak extension
  • The regex substitution acts on the implicit variable, which are the contents of the file, line-by-line
like image 50
Zaid Avatar answered Sep 21 '22 13:09

Zaid


None of the existing answers here have provided a complete example of how to do this from within a script (not a one-liner). Here is what I did:

rename($file, $file . '.bak'); open(IN, '<' . $file . '.bak') or die $!; open(OUT, '>' . $file) or die $!; while(<IN>) {     $_ =~ s/blue/red/g;     print OUT $_; } close(IN); close(OUT); 
like image 33
cmbryan Avatar answered Sep 21 '22 13:09

cmbryan