Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

deleting first 9 lines from every file in directory 2

Status
Not open for further replies.

jcarrott

Programmer
May 28, 2009
130
US
I need to delete the first 9 lines of every file in a directory. I know that the list of files has "." in $files[0] and ".." in $files[1], so I started with a $files[2] as the first file, but I did not delete any lines from the files.

Here is the code I used,

opendir(DIR, "D:\\EDI_Inv");
@files = readdir(DIR);
closedir(DIR);

# this deletes the first 9 lines of each file
for ($i = 2; $i < @files; $i++)
{
$name = @files[$i];
open(FH,$name);
@array = <FH>;
close FH;
open(OUT,">$name");
print OUT @array[9..$#array];
close OUT;

}

This reads the list of files just fine, but it does not delete the first 9 lines.

Does anybody have any ideas of what I did wrong?
 
All you have done is open the files for reading.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
I think this line:

Code:
    $name = @files[$i];

Should read:

Code:
    $name = $files[$i];

Although the $name variable is unnecessary when you can just use $files[$i].

Annihilannic.
 
oops.... excuse my last comment, not sure how I missed your OUT filehandle that does open the file for create/overwrite. See if this helps:

Code:
opendir(DIR, "D:\\EDI_Inv") or die "$!";
my @files = readdir(DIR);
closedir(DIR);

# this deletes the first 9 lines of each file
for ($i = 2; $i < @files; $i++)
{
    my $name = $files[$i] or die "No filename in <$files[$i]>\n";
    open(FH,$name) or die "Can't open $name : $!";
    my @array = <FH>;
    close FH;
    sleep(1);
    open(OUT, ">$name") or die "Can't open $name for overwriting: $!";
    print OUT @array[9..$#array];
    close OUT;
}

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
I wouldn't rely on having the '.' and '..' directories in the first two places; also if you have subdirectories in your directory you'll get problems (Kevin's code will die).
Also note that your code (and Kevin's one) will only work if the named directory is the current one.
So I would replace the second line with the following one
Code:
my@files=grep{-f}map{"D:/EDI_Inv/$_"}readdir(DIR);

Franco
: Online engineering calculations
: Magnetic brakes for fun rides
: Air bearing pads
 
Thank you both, the sleep(1) worked, and the grep allowed me to start with the array value of 0.
This works great thank you both.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top