Avatar billede carnudo Nybegynder
03. oktober 2001 - 10:54 Der er 5 kommentarer og
1 løsning

Replacing a word in a folder with subfolders and files.

I have a folder in LINUX called /home/mamon
and inside /home/mamon there are 100 files and other directories like this:

/home/mamon>
DirX
DirY
DirZ
fil1
fil2
fil3
fil4
fil5
...
...
...
fil100

As you can see the files do not have extension in linux.
In fil1 to fil100 it is writen \"I like rise\"
and I want to replace the word \"rise\" for \"fish\"
Inside the Directories DIRX DIRY and DIRZ there are also files with the same text which I also want to replace with \"fish\".

How can I do that?
Avatar billede yellow Nybegynder
05. oktober 2001 - 15:26 #1
I made a sample script to do it. This script will take all files in /home/mamon and replace all instances of rice with fish ( even \'riceman\' with \'fishman\' ). Also, it will take all files in all subdirectories to /home/mamon/ and replace rice with fish.
If you want only to take files names filx,filxx etc, use grep in the \'open\' statements. If you want to change when \'rice\' should be replaced with \'fish\', change the regexp.

$dir = \'C:\\home\\mamon\';
opendir( DIR, $dir ) or die $!;
my @files = readdir( DIR );
closedir( DIR );
{ undef($/);
        foreach my $file(@files){
          if( opendir( DIR, \"$dir\\\\$file\" ) ){
              @subfiles = readdir( DIR );
              foreach my $subfile(@subfiles){
                checkFile( \"$dir\\\\$file\\\\$subfile\" );   
              }
            closedir( DIR );
          }
          else{
            checkFile( \"$dir\\\\$file\" );
          }
  }
}
sub checkFile(){
    my $file = shift;
  if( open( INFILE, $file ) ){
      my $fileContent = <INFILE>;
      $fileContent =~ s/rice/fish/ig;
      close(INFILE);
      open( OUTFILE, \">$file\" );             
        print OUTFILE $fileContent;
      close( OUTFILE );
  }   
}
Avatar billede carnudo Nybegynder
05. oktober 2001 - 19:09 #2
This looks beautiful, I will test and comeback to you. I want to thank you very much for your time and help.
Avatar billede carnudo Nybegynder
14. oktober 2001 - 21:33 #3
Sorry it did not work.
Avatar billede carnudo Nybegynder
04. november 2001 - 01:19 #4
did not work
Avatar billede carnudo Nybegynder
28. december 2001 - 10:56 #5
closing case
Avatar billede carnudo Nybegynder
28. december 2001 - 10:56 #6
closed
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester