#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2003
    Posts
    29
    Rep Power
    0

    how to rename files


    HI all, how to use the 'mv' command in a perl script to rename files in a directory so that when I execute the script:

    scriptname zonk plink

    it will rename files zonk.c zonk .o and zonk to plink .c plink.o plink. The following code can only rename all the files in the directory to the same name but not to different extensions.
    (e.g zonk zonk zonk & not zonk.c zonk.o zonk)
    Can anybody help? Thanks.

    #!/usr/bin/perl -w
    >
    > $dir= "./";
    > print "$dir\n";
    > #Checkthe present of arguments
    > if (@ARGV != 3){
    > print "Argument absent\n";
    > print "usage: $0 mvname file1 file2\n";
    > exit
    > }
    > #assign files input in command line
    > $file1=$ARGV[1];
    > $file2=$ARGV[2];
    >
    >
    > opendir (CURRENTDIR, "$dir") or die "Can't open directory:$!\n";
    > while (defined($tempfile = readdir(CURRENTDIR))){
    > #Check the present of the target files
    > if($tempfile =~ /^$file1/){
    > push @targetfile,$tempfile;
    > }else{
    > push @unmatchfile, $tempfile;
    > }
    > }
    > closedir(CURRENTDIR);
    >
    > #Print when NONE of the files in directory are matched
    > if (scalar(@targetfile) == 0){
    > print "File of initial name, $file1 ,NOT found in the directory.\n";
    > print "Try the files listed below\n";
    > print "@unmatchfile\n";
    >}
    > #Change files to new names and print the list
    > foreach $item (@targetfile){
    > $len = length ($file1);
    > $leadfile = $item;
    > substr ($item,0,$len,$file2);
    > `mv $leadfile $item`;
    > print"$item ";
    > }
    > print "\n";
  2. #2
  3. watch for flying fingers
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2003
    Location
    Rocket City, USA
    Posts
    819
    Rep Power
    382
    This forum has a search function that is often helpful.

    File Renaming
    how to rename files in dir using mv command

IMN logo majestic logo threadwatch logo seochat tools logo