How to batch rename 10,000 folders on a Linux server?

Discussion in 'Site & Server Administration' started by yevlesh, Jun 18, 2007.

  1. #1
    I need to rename approximately 10,000 folders located on a Linux server. All I need to do is replace the space in the folder name (as in Big House) with an underscore (turning it into Big_House for example).

    How can I automate this process?
     
    yevlesh, Jun 18, 2007 IP
  2. agnivo007

    agnivo007 Peon

    Messages:
    4,290
    Likes Received:
    289
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I guess shell scripting (or through perl) can make it easy for you.
    I hope some linux guru would come to your rescue in this thread soon. :)
     
    agnivo007, Jun 19, 2007 IP
  3. CodyRo

    CodyRo Peon

    Messages:
    365
    Likes Received:
    15
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Pop the below code in a php script and chmod it so it can execute (chmod +x). Please test it out in a controlled environment first, I didn't really do any real world testing on it.

    You might want to add set_time_limit() if the script is timing out because of so many folders.

    
    #!/usr/bin/php -q
    
    <?php
    
    $count = 0;
    
    if (($dh = opendir("./")))
    {
        while (($file = readdir($dh)) !== false)
        {
           if ($file == "." || $file == "..") continue;
           if (!is_dir($file)) continue;
    
           $new_filename = str_replace(" ", "_", $file);
           rename($file, $new_filename);
           $count++;
           echo "Renaming $file -> $new_filename \n";
        }
        echo "Renamed: $count files \n";
    }
    
    ?>
    
    
    PHP:
     
    CodyRo, Jun 19, 2007 IP
  4. yevlesh

    yevlesh Active Member

    Messages:
    162
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    58
    #4
    Thank you very much! The script worked perfectly - all the folders were correctly renamed in about 5 mins or so!
    That script was a huge timesaver - thanks again

     
    yevlesh, Jun 19, 2007 IP
  5. agnivo007

    agnivo007 Peon

    Messages:
    4,290
    Likes Received:
    289
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Hmm...good one codyro :)
     
    agnivo007, Jun 19, 2007 IP
  6. SumitBahl

    SumitBahl Reign of Chaos

    Messages:
    5,170
    Likes Received:
    596
    Best Answers:
    0
    Trophy Points:
    310
    #6
    I have a similar problem.
    Is there any solution that would replace the references of those folders and files in the HTML files?
     
    SumitBahl, Jun 19, 2007 IP