in reply to Re: Search & Replace in subdirectory files
in thread Search & Replace in subdirectory files

Hello Rina

The following code uses File::Find and Tie::File. Note that Tie::File reads each line into an array so you can attempt a substitution. It also edits the file in place so that the original file will be changed to one with the substitutions. Be *careful* of this code as it will change your original files! Maybe set up a dummy directory with some dummy files to test it. I did to test this script! Note that this will change all files in the top directory, /some/dir_name, and goes through each sub_directory looking at all the files.

#!/usr/bin/perl use strict; use warnings; use Tie::File; use File::Find; my @directories_to_search = ("/some/dir_name"); find(\&wanted, @directories_to_search); sub wanted { if (-f) { tie my @array, 'Tie::File', $_ or die $!; s/\$Log/\$History/gi for @array; } }
Hope this helps

Chris

Replies are listed 'Best First'.
Re: Re: Re: Search & Replace in subdirectory files
by Anonymous Monk on Apr 23, 2004 at 23:47 UTC
    Oops, should have included this line in the wanted function
    sub wanted { if (-f) { tie my @array, 'Tie::File', $_ or die $!; s/\$Log/\$History/gi for @array; untie @array; } }
    Also noticed your reg expression may not be what you want - may be better stated
    s/^\$Log\b/\$History/
    That is $Log only appears as the first item in the line of text and always uses the same letter capitalization. So, you wouldn't need the g modifier because the word only appears once (at the beginning) and you wouldn't want the i option because the case doesn't (?) change. I put in the \b because in $Log, there shuldn't be any following word characters (judging from the sample you posted).

    Chris

Re: Re: Re: Search & Replace in subdirectory files
by Rina (Initiate) on Apr 26, 2004 at 16:23 UTC
    Chris,

    I was very excited to try your suggestion, but it doesn't work with my current version of perl. So...#1 - how do I find out what version of perl is installed?

    What minimum version should I upgrade to? First thing today I tried to download & install version 5.8.4 from perl.com (to my own machine before putting it on the server). I added this new perl directory to my environment variables, but still getting an error that "Can't locate Tie/File.pm in @INC at LogHist2.pl (my script name) line 4."

    Thanks again
Re: Re: Re: Search & Replace in subdirectory files
by Rina (Initiate) on May 18, 2004 at 21:27 UTC
    Now that I've upgraded the perl version, this script works. Thank you!