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?
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 );
}
}