Re: Adding a line in a file inside many directories
- From: Ved <vedpsingh@xxxxxxxxx>
- Date: Fri, 29 Jun 2007 08:30:52 -0000
On Jun 29, 12:38 pm, Joe Smith <j...@xxxxxxxxx> wrote:
Ved wrote:
I have a 150 directories, each having a file "kat.s" in them.
I have names of all these directories in a text file
"list_of_dir.txt".
I have to open the each of "kat.s" in all the 150 directories and add
a line(say "ABCD" at line number 20) in each of them.
Separate the problem into two parts:
1) A loop that goes through the file names, one at a time.
2) A subroutine that deals with the process of editing a single file.
my $dir_list = 'list_of_dir.txt';
my $file_to_change = 'kat.s';
open my $fh,'<',$dir_list or die "Cannot read $dir_list: $!\n";
while (my $dir = <$fh>) {
chomp $dir;
my $file = "$dir/$file_to_change";
if (-e $file) {
process_one_file($file);
} else {
warn "File $file does not exist; skipping\n";
}
}
sub process_one_file {
my $file = shift;
print "Processing $file\n";
...
}
Unless you want to deal with the magic of perl's $^I variable (perldoc -q -i),
go with Gunnar's suggestion (perldoc Tie::File) for process_one_file.
-Joe
Hey Guys,
Thanks for the replies.
Joe I tried the code. This is what it is returning
######
File green_mcs020 /kat.s does not exist; skipping
File green_mcs0_40 /kat.s does not exist; skipping
File green_mcs0_20L /kat.s does not exist; skipping
File green_mcs0_40_20U /kat.s does not exist; skipping
#######
I think it is because the whitespace between the directory and file.
Directory file
green_mcs020(whitespace)/kat.s
Am I right ?
I did some chomp in the code but it didn't help. From where this
whitespace is coming in ?
After adding chomps code looks like this now :
#!/usr/local/bin/perl
use strict;
use warnings;
my $dir_list = 'my.tests';
chomp $dir_list ; ## added by me
my $file_to_change = 'katana.sv';
chomp $file_to_change ; ## added by me
open my $fh,'<',$dir_list or die "Cannot read $dir_list: $!\n";
while (my $dir = <$fh>) {
chomp $dir;
my $file = "$dir/$file_to_change";
print $file ; #added by me
if (-e $file) {
process_one_file($file);
} else {
warn "File $file does not exist; skipping\n";
}
}
sub process_one_file {
my $file = shift;
print "Processing $file\n";
# ...
}
.
- Follow-Ups:
- Re: Adding a line in a file inside many directories
- From: Ved
- Re: Adding a line in a file inside many directories
- From: Gunnar Hjalmarsson
- Re: Adding a line in a file inside many directories
- References:
- Adding a line in a file inside many directories
- From: Ved
- Re: Adding a line in a file inside many directories
- From: Joe Smith
- Adding a line in a file inside many directories
- Prev by Date: Re: Problem with PERL function
- Next by Date: Re: DBIx::Simple, fails with no error (not CGI this time!)
- Previous by thread: Re: Adding a line in a file inside many directories
- Next by thread: Re: Adding a line in a file inside many directories
- Index(es):
Relevant Pages
|
|