Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

renaming all files in a directory

by Aldebaran (Curate)
on Jun 11, 2012 at 07:39 UTC ( #975506=perlquestion: print w/replies, xml ) Need Help??

Aldebaran has asked for the wisdom of the Perl Monks concerning the following question:

Hello monks, I thought I knew how to do this, but apparently I don't:

$ perl mpj2.pl file: /home/dan/Desktop/upload $ ls /home/dan/Desktop/upload 179148_10150875347426275_161694845_n.jpg 484180_10150840098410957_750520549_n.jpg 526160_329491527117931_212574393_n.jpg 532875_317265865025966_675027772_n.jpg 540009_426335457388417_562960017_n.jpg 543406_10150615290746269_1527898960_n.jpg 559622_10150811371179228_713865817_n.jpg 576895_319150664834725_665940778_n.jpg $ cat mpj2.pl #!/usr/bin/perl -w use strict; my @files = </home/dan/Desktop/upload>; my $counter = 0; for my $img (@files) { print "file: $img\n"; $counter++; my $filename = "image_". "$counter"; } $

Had I been successful, I would have seen these files all renamed to the concatenation of image_ and a number. Thanks for your comment.

Replies are listed 'Best First'.
Re: renaming all files in a directory
by CountZero (Bishop) on Jun 11, 2012 at 08:50 UTC
    Do you think that putting the new filename into the variable $filename will magically change the name of the file on your harddisk?

    Have a look at File::Copy, more especially the move function.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

    My blog: Imperial Deltronics

      When you ask the question like that, no, but I've made strides:

      $ perl mpj4.pl file: /home/dan/Desktop/upload/382432_10150873103536275_1105470601_n.j +pg ext: jpg filename: /home/dan/Desktop/upload/image_1.jpg file: /home/dan/Desktop/upload/542274_470102786337441_1974797173_n.jpg ext: jpg filename: /home/dan/Desktop/upload/image_2.jpg file: /home/dan/Desktop/upload/safe_image.php.jpeg ext: jpeg filename: /home/dan/Desktop/upload/image_3.jpeg $ cat mpj4.pl #!/usr/bin/perl -w use strict; my $path = '/home/dan/Desktop/upload/'; my @files = <$path*>; my $counter = 0; for my $img (@files) { $counter++; print "file: $img\n"; my $ext = ($img =~ m/([^.]+)$/)[0]; print "ext: $ext\n"; my $filename = "$path" . "image_". "$counter" . '.' . "$ext"; print "filename: $filename\n"; rename ($img, $filename) or warn "couldn't rename $img to $filename: + $!\n"; } $

      The situation that was really throwing me for a loop was that I'd write something to rename things, and then they'd all disappear. Until I put the asterisk in the diamond brackets, the directory did too! From what I read last night, this is something that happens to every perl learner at some point. I'm sure there's other ways of doing this, and I'd love to see them. I'll take a look a look at File::Copy when I get back to it.

      I wanted to say a few words on where I'm going with this. I want to combine these scripts so as to have a directory that has renamed images, but with the correct extension:

      $ perl lh1.pl downloaded 4 images from https://sites.google.com/site/lutherhavennm/m +ission to folder site_8 $ cat lh1.pl #!/usr/bin/perl -w # creates a new directory and downloads images from url to it # perlmonks node 965537; thx aaron and A.M. use strict; use feature ':5.10'; use WWW::Mechanize; use LWP::Simple; use Errno qw[ EEXIST ]; # get information about images my $domain = 'https://sites.google.com/site/lutherhavennm/mission'; my $m = WWW::Mechanize->new(); $m->get($domain); my @list = $m->images(); # create new folder and download images to it. my $counter = 0; my $dir = &mk_new_dir; for my $img (@list) { my $url = $img->url_abs(); $counter++; my $filename = $dir . "/image_" . $counter; getstore( $url, $filename ) or die "Can't download '$url': $@\n"; } # output print "downloaded ", $counter, " images from ", $domain, "\n"; print "to folder ", $dir, "\n"; sub mk_new_dir { my $counter2 = 1; while (1) { my $word = "site"; my $name = $word . '_' . $counter2++; if ( mkdir $name, 0755 ) { return $name; # success, return new dir name } else { next if $!{EEXIST}; # mkdir failed because file exists die sprintf "(%d) %s", $!, $!; # other failure; bail ou +t! } } } $

      After that, I want to create an html file that will have the stubouts for these images and their caption, but that has to be tomorrow. Cheers,

        An alternative way to make the "next" directory:
        use Modern::Perl; use File::Find::Rule; my $directory = 'c:/data/strawberry-perl/perl/script-chrome'; my $dir_pattern = 'test_'; my $next = ( sort { $b <=> $a } map { /(\d+)$/; $1 } File::Find::Rule->directory ->name( "$dir_pattern*" ) ->in( $directory ) )[0] + 1; mkdir "$directory/$dir_pattern$next", 0755 or die "Could not make dire +ctory $directory/$dir_pattern$next";

        CountZero

        A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

        My blog: Imperial Deltronics
Re: renaming all files in a directory
by Anonymous Monk on Jun 11, 2012 at 08:48 UTC

      I took a look at your thread at that link but don't necessarily follow it all yet. I don't think I want to glob for any of this. Does this look like a fairly robust way to download images and rename them uniformly but with correct filetypes?

      $ perl lh2.pl img: WWW::Mechanize::Image=HASH(0xa1fdc5c) https://sites.google.com/site/lutherhavennm/_/rsrc/1255408739014/missi +on/Attachment3.jpg?height=278&width=420 ext: jpg?height=278&width=420 ext: jpg img: WWW::Mechanize::Image=HASH(0xa207784) https://sites.google.com/site/lutherhavennm/_/rsrc/1255386973661/missi +on/Picture1.jpg?height=279&width=420 ext: jpg?height=279&width=420 ext: jpg img: WWW::Mechanize::Image=HASH(0xa2078ec) https://sites.google.com/site/lutherhavennm/_/rsrc/1255408642180/missi +on/Attachment10.jpg?height=280&width=420 ext: jpg?height=280&width=420 ext: jpg img: WWW::Mechanize::Image=HASH(0xa2074dc) https://sites.google.com/site/lutherhavennm/_/rsrc/1255387202014/missi +on/Looking%20up%20at%20the%20Bldg.JPG?height=315&width=420 ext: JPG?height=315&width=420 ext: JPG downloaded 4 images from https://sites.google.com/site/lutherhavennm/m +ission to folder site_17 $ cat lh2.pl #!/usr/bin/perl -w use strict; use feature ':5.10'; use WWW::Mechanize; use LWP::Simple; use Errno qw[ EEXIST ]; # get information about images my $domain = 'https://sites.google.com/site/lutherhavennm/mission'; my $m = WWW::Mechanize->new(); $m->get($domain); my @list = $m->images(); # create new folder and download images to it. my $counter = 0; my $dir = &mk_new_dir; for my $img (@list) { print "img: $img\n"; my $url = $img->url_abs(); print "$url \n"; my $ext = ($url =~ m/([^.]+)$/)[0]; print "ext: $ext\n"; $ext =~ s/\?.+//; print "ext: $ext\n"; $counter++; my $filename = $dir . "/image_" . $counter. '.' . $ext; getstore( $url, $filename ) or die "Can't download '$url': $@\n"; } # output print "downloaded ", $counter, " images from ", $domain, "\n"; print "to folder ", $dir, "\n"; sub mk_new_dir { my $counter2 = 1; while (1) { my $word = "site"; my $name = $word . '_' . $counter2++; if ( mkdir $name, 0755 ) { return $name; # success, return new dir name } else { next if $!{EEXIST}; # mkdir failed because file exists die sprintf "(%d) %s", $!, $!; # other failure; bail ou +t! } } } $

      Is this how all images on the net really look to servers, with the size information on them as well? Where do I find information about the url_abs() method here? I don't see it in either of the modules used.

        No.

        And the first few lines look as though you're trying to make something up as you go; don't know how to cut'n'paste; or are yanking our chains.

        Or, maybe, need this reminder:

        Please, separate your record of output from your code.
Re: renaming all files in a directory
by Anonymous Monk on Jun 11, 2012 at 13:53 UTC
    Tip: Use a canned CPAN package like File::Find to find all the files you want to rename, unless there is a truly outrageous number of them, and put the file names into a list or array before going back through that list to move or rename the files. On some operating systems manipulating files in the directory that you are scanning can cause files to be found more than once and/or for other files to be skipped.

      thx A.M., these files aren't hard for me to find because they're ones that I will have caused to have been recently-downloaded. I almost want to use it as my soapbox for "The Day in Internet Images."

Re: renaming all files in a directory
by sreekanc (Initiate) on Jun 11, 2012 at 08:10 UTC

    Hope this helps.

    $ ls 179148_10150875347426275_161694845_n.jpg 532875_317265865025966_675027772_n.jpg 559622_10150811371179228_713865817_n.jpg 484180_10150840098410957_750520549_n.jpg 540009_426335457388417_562960017_n.jpg 576895_319150664834725_665940778_n.jpg 526160_329491527117931_212574393_n.jpg 543406_10150615290746269_1527898960_n.jpg $ ls | perl -nle 'BEGIN {$counter=0}; $old=$_;$new="image"."$counter"; +rename($old,$new);$counter++;' $ ls image0 image1 image2 image3 image4 image5 image6 ima +ge7 $

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://975506]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2022-12-09 23:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?