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

How difficult would it be to write a script in Perl to scan entire trees looking to replace every occurrence of a command such as 'Name' with another command such as 'FullName' for a given file type such as *.INF? Does anyone know how to do this?
  • Comment on Replacing one string within a file with another string

Replies are listed 'Best First'.
Re: Replacing one string within a file with another string
by mwp (Hermit) on Aug 18, 2000 at 02:58 UTC

    This is difficult to make efficient, simply because you have to read in the full contents of every file to perform the replacement operation. Not to mention that you might wind up replacing the wrong thing! Here are some guidlines you can use to get you started, at least:

    1. Use File::Find to get a list of files. This verily automates the process of recursing through a directory tree and extracting a specific list of filenames. You can even read this for an example I wrote earlier today.
    2. Use `local()' to modify the value of $/ (the input line separator), ala local($/) = undef. This will allow you to slurp in a whole file into a scalar, then you can `study()' that scalar, perform a regex, and dump it back out to a file.
    3. Make backups. All the decent "Cross-File Find & Replace" engines at least give you the options of making backups. A simple system('cp', $filename, $filename .".bak") should do the trick.

Good luck!

Alakaboo

RE: Replacing one string within a file with another string
by Russ (Deacon) on Aug 18, 2000 at 03:15 UTC
    perl -i.bak -ne 's/Name/FullName/g; print' *.INF

    See File::Find for the ability to scan an entire tree.

    If I were on a *NIX box, I would use:
    perl -i.bak -ne 's/Name/FullName/g; print' `find . -name *.INF`
    find in backticks to traverse the tree.

    It's not cross-platform like tye's solution below, but I'm almost as big a Linux bigot as I am a Perl bigot...

    :-)

    Russ
    Brainbench 'Most Valuable Professional' for Perl

      But don't you wish there was a better way to mix the two?

      perl -i.bak -pMFile::find -e 'BEGIN{find(sub{push@ARGV,$File::find::na +me if /[.]inf$/i},".")}s/Name/FullName/g'

      just seems like too much work!.

              - tye (but my friends call me "Tye")
        Nice use of -M, BEGIN{} and @ARGV.

        Too much work? Perhaps, but nice, anyway!

        Russ
        Brainbench 'Most Valuable Professional' for Perl