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

I have a list of files and there is string in the file (in multiple areas) as so CLASSATTRIBUTES , i want to convert that to all lowercase and then leave that file in the path i picked it up from ... can anyone help me thanks you everyone
  • Comment on please help on subsituting a pattern in a file

Replies are listed 'Best First'.
Re: please help on subsituting a pattern in a file
by sauoq (Abbot) on Jun 05, 2003 at 20:27 UTC
    perl -i.bak -pe 's/(CLASSATTRIBUTES)/lc $1/e' file1 file2 /path/to/file/3

    That has some caveats. First, you shouldn't use a glob as an argument to that for security reasons. Also, that will create backup files named with .bak, just in case you make a mistake. Finally, if that string appears more than once and you want all instances lowercased, add a /g to the substitution.

    -sauoq
    "My two cents aren't worth a dime.";
    
Re: please help on subsituting a pattern in a file
by DamnDirtyApe (Curate) on Jun 05, 2003 at 20:25 UTC

    This can be done from the command line:

    perl -p -i.bak -e 's:CLASSATTRIBUTES:classattributes:g' *

    ...though I'm not sure whether that's an option for you or not.

    Update: Ah yes, please read the excellent comments below. If you're doing this from within a script, this works:

    my @files = qw( foobar zoot ); for my $file ( @files ) { ## Read the contents of the file open FILE, "<$file"; my $contents; do { local $/; $contents = <FILE>; }; close FILE; ## Make your changes $contents =~ s:CLASSATTRIBUTES:classattributes:g; ## Write the modified contents back to the file open FILE, ">$file"; print FILE $contents; close FILE; }

    _______________
    DamnDirtyApe
    Those who know that they are profound strive for clarity. Those who
    would like to seem profound to the crowd strive for obscurity.
                --Friedrich Nietzsche

      Don't use a -p and a * like that unless you know what you are doing. See the discussion starting at Dangerous Diamonds! for an explanation.

      -sauoq
      "My two cents aren't worth a dime.";