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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Renaming files to not had a space in them. 1

Status
Not open for further replies.

DunLudjin

Technical User
Jun 17, 2009
11
US
I'm trying to use Perl for text processing for Latex. One of the big problems I have is spaces in file names in both in the current and sub directories for PDF files. I'm trying to use Perl to detect the PDF file in all the subdirectories and rename the file removing the spaces and putting in a dash instead.

I've got most of the program, I just cannot get the files
to copy. Any help would be appreciated.

The code I have is as follows:
----------------------------------------------
#!/usr/bin/perl -w
use warnings;
use strict;

use File::Find;
use File::Copy;

my @old;
my @new;
my %test;

find(\&find_pdfs, ".");

sub find_pdfs
{
my $file = $_;
chomp($file);

if ($file =~ /pdf$/) {
push @old,"$File::Find::dir/$_\n" if -f ;
}
}

@new = @old;

foreach my $i (@new) {
$i =~ s/ /\-/g;
}


@test{@old}=@new;

for (keys %test){
print "$_ and $test{$_}\n";
copy("$_","$test{$_}") or die "File cannot be copied.\n";
}
--------------------------------------

For example, in the current directory I have a file "J9161 plc.pdf". I want to change this to "J9161-plc.pdf".

Currently I can get the file name "./J9161 plc.pdf" and the replacement file name "./J9161-plc.pdf" but I get the following error when I use the copy command:

Unsuccessful stat on filename containing newline at c:/Perl/lib/File/Copy.pm line 112.


Any thoughts?
 
How about something like this?
Code:
use File::Find;
use File::Copy;

find(\&rename_txts, "./txt2/");

sub rename_txts {
	if (/\.txt$/) {
		my $new_name = $_;
		$new_name =~ y/ /-/;
		print "$File::Find::name to $new_name\n";
		move $_, $new_name;
	}
}
 
This worked perfectly! Now I need to figure out exactly what it does...

Thanks
 
don't see that "y" operator much in perl:

$new_name =~ y/ /-/;

same as:

$new_name =~ tr/ /-/;

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top