azaria has asked for the wisdom of the Perl Monks concerning the following question:

Hi there, I would like to know if there is any command line that I can substitue a phrase from files resides under a given root directory ? Thanks Azaria

Replies are listed 'Best First'.
Re: file phrase substitutation
by Zaxo (Archbishop) on Nov 01, 2005 at 19:51 UTC

    Is this what you mean?

    $ perl -pi -e's/this phrase/that locution/g' /path/to/*.txt $
    If you want something different you'll have to be more specific.

    After Compline,
    Zaxo

      First thanks for your reply. in case that all files are not resides under the same level this would not work correctly, I might use - find <dir> -name "*" -exec perl -pi -e's/this phrase/that locution/g' {} \; Azaria

        Here's a solution that does it all in perl:

        #!/usr/bin/perl use warnings; use strict; use File::Find; use Tie::File; find (\&replace,"/path/to/directory"); sub replace { my $cur_file=$File::Find::name; return if (!-f $cur_file || !-w $cur_file); tie my @file_content,'Tie::File',$cur_file or die "Couldn't tie file $cur_file"; for (@file_content) { s/this phrase/that locution/g; } }

        You may want to read the Tie::File perldoc regarding file locking and memory consumption.

        And just for completeness, here's a solution that does it all without perl:

        find this/ -type f -exec sed -i 's/gg/dd/g' {} \;

        Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- Brian W. Kernighan