Solved Open & Replace string in Multiple files-PERL

November 29, 2011 at 07:35:19
Specs: Windows XP
i want a perl program which will open multiple of .txt files from a folder and replace contents within it...i have to rename ABC into DEF in every files in that folder..i have the program for replacing but it can be done only for a single file and that too the full name of the file have to be mentioned...i want to read multiple txt files and make the substitution..

The snippet:

#! /usr/bin/perl -w

open (IN, "+<CHECK.txt");

@file = <IN>;

seek IN,0,0;

foreach $file (@file){
$file =~ s/ABC/DEF/g;
$file =~ s/FAIL/ /g;
print IN $file;
close IN;


See More: Open & Replace string in Multiple files-PERL

Report •

November 29, 2011 at 13:56:31
✔ Best Answer
Here is a wrapper script that you can place around your code. This was developed under Solaris unix so I don't know if it will work with windows. You will probably have to use the window's directory seperator \ which is different from unix:

Your open will probably look something like:

open (IN, "$directory\$file");

use strict;
use warnings;

# change to your folder name
my $directory = '/tmp';

opendir (DIR, $directory) or die $!;
while (my $file = readdir(DIR)) {
   chomp $file;
   # only want files
   next unless (-f "$directory/$file");
   # only want files ending with .txt
   next unless ($file =~ m/\.txt$/);

# Put your perl code here
   print "$directory/$file\n";

Report •
Related Solutions

Ask Question