Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 20th, 2012  |  syntax: None  |  size: 0.62 KB  |  hits: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Search and replace a particular string in a file using Perl [closed]
  2. #!/usr/bin/perl -w
  3.  
  4. use strict;
  5.  
  6. open(FILE, "</tmp/yourfile.txt") || die "File not found";
  7. my @lines = <FILE>;
  8. close(FILE);
  9.  
  10. my @newlines;
  11. foreach(@lines) {
  12.    $_ =~ s/<PREF>/ABCD/g;
  13.    push(@newlines,$_);
  14. }
  15.  
  16. open(FILE, ">/tmp/yourfile.txt") || die "File not found";
  17. print FILE @newlines;
  18. close(FILE);
  19.        
  20. perl -pi.back -e 's/<PREF>/ABCD/g;' inputfile
  21.        
  22. #!/usr/bin/perl
  23.  
  24. use strict;
  25. use warnings;
  26.  
  27. $^I = '.bak'; # create a backup copy
  28.  
  29. while (<>) {
  30.    s/<PREF>/ABCD/g; # do the replacement
  31.    print; # print to the modified file
  32. }
  33.        
  34. ./script.pl input_file