2

I'm trying to create a process that renames all my filenames to Camel/Capital Case. The closest I have to getting there is this:

perl -i.bak -ple 's/\b([a-z])/\u$1/g;' *.txt # or similar .extension.

Which seems to create a backup file (which I'll remove when it's verified this does what I want); but instead of renaming the file, it renames the text inside of the file. Is there an easier way to do this? The theory is that I have several office documents in various formats, as I'm a bit anal-retentive, and would like them to look like this:

New Document.odt
Roffle.ogg
Etc.Etc
Bob Cat.flac
Cat Dog.avi

Is this possible with perl, or do I need to change to another language/combination of them?

Also, is there anyway to make this recursive, such that /foo/foo/documents has all files renamed, as does /foo/foo/documents/foo?

1
  • You didn't specify what you their current forms are.
    – Axeman
    Mar 25, 2009 at 1:31

6 Answers 6

9

You need to use rename .

Here is it's signature:


rename OLDNAME,NEWNAME

To make it recursive, use it along with File::Find


use strict;
use warnings;
use File::Basename;
use File::Find;

#default searches just in current directory
my @directories = (".");

find(\&wanted,  @directories);

sub wanted {
  #renaming goes here
}

The following snippet, will perform the code inside wanted against all the files that are found. You have to complete some of the code inside the wanted to do what you want to do.

EDIT: I tried to accomplish this task using File::Find, and I don't think you can easily achieve it. You can succeed by following these steps :

  • if the parameter is a dir, capitalize it and obtain all the files

  • for each file, if it's a dir, go back at the beginning with this file as argument

  • if the file is a regular file, capitalize it

Perl just got in my way while writing this script. I wrote this script in ruby :


require "rubygems"
require "ruby-debug"

# camelcase files

class File
    class << self
        alias :old_rename :rename
    end

    def self.rename(arg1,arg2)
        puts "called with #{arg1} and #{arg2}"
        self.old_rename(arg1,arg2)
    end
end

def capitalize_dir_and_get_files(dir)
    if File.directory?(dir)
        path_c          = dir.split(/\//)
        #base           = path_c[0,path_c.size-1].join("/")
        path_c[-1].capitalize!  
        new_dir_name    = path_c.join("/")
        File.rename(dir,new_dir_name)
        files = Dir.entries(new_dir_name) - [".",".."]
        files.map! {|file| File.join(new_dir_name,file)}
        return files 
    end
    return []
end

def camelize(dir)
    files = capitalize_dir_and_get_files(dir)
    files.each do |file|
        if File.directory?(file)
            camelize(file.clone)
        else
            dir_name    = File.dirname(file)
            file_name   = File.basename(file)
            extname     = File.extname(file)
            file_components = file_name.split(/\s+/)
            file_components.map! {|file_component| file_component.capitalize}           
            new_file_name = File.join(dir_name,file_components.join(" "))
            #if extname != ""
            #   new_file_name += extname
            #end
            File.rename(file,new_file_name)
        end
    end
end

camelize(ARGV[0])

I tried the script on my PC and it capitalizes all dirs,subdirs and files by the rule you mentioned. I think this is the behaviour you want. Sorry for not providing a perl version.

4
  • search.cpan.org/dist/File-Find-Rule/lib/File/Find/Rule.pm is prettier than File::Find, but YMMV.
    – ephemient
    Mar 24, 2009 at 16:01
  • I pretty much grew up using File::Find :). I like it more.
    – Geo
    Mar 24, 2009 at 16:03
  • Global symbol "@directories" requires explicit package name at bob.pl line 5. Execution of bob.pl aborted due to compilation errors. Tried to run bob.pl(with latest edit) ^ is result.
    – r00t
    Mar 24, 2009 at 16:14
  • perl -MFile::Find -e'finddepth(sub{($a=$_)=~s/\b([a-z])/\u$1/g&&rename$_,$a},@ARGV?@ARGV:".")'
    – ephemient
    Feb 5, 2010 at 5:16
5

Most systems have the rename command ....

NAME rename - renames multiple files

SYNOPSIS rename [ -v ] [ -n ] [ -f ] perlexpr [ files ]

DESCRIPTION "rename" renames the filenames supplied according to the rule specified as the first argument. The perlexpr argument is a Perl expression which is expected to modify the $_ string in Perl for at least some of the filenames specified. If a given filename is not modified by the expression, it will not be renamed. If no filenames are given on the command line, filenames will be read via standard input.

   For example, to rename all files matching "*.bak" to strip the extension, you might say

           rename 's/\.bak$//' *.bak

   To translate uppercase names to lower, you’d use

           rename 'y/A-Z/a-z/' *

OPTIONS -v, --verbose Verbose: print names of files successfully renamed.

   -n, --no-act
           No Action: show what files would have been renamed.

   -f, --force
           Force: overwrite existing files.

AUTHOR Larry Wall

DIAGNOSTICS If you give an invalid Perl expression you’ll get a syntax error.

3

Since Perl runs just fine on multiple platforms, let me warn you that FAT (and FAT32, etc) filesystems will ignore renames that only change the case of the file name. This is true under Windows and Linux and is probably true for other platforms that support the FAT filesystem.

Thus, in addition to Geo's answer, note that you may have to actually change the file name (by adding a character to the end, for example) and then change it back to the name you want with the correct case.

If you will only rename files on NTFS filesystems or only on ext2/3/4 filesystems (or other UNIX/Linux filesystems) then you probably don't need to worry about this. I don't know how the Mac OSX filesystem works, but since it is based on BSDs, I assume it will allow you to rename files by only changing the case of the name.

2
  • Unlike the BSD filesystems, though, OS X's default HFS+ is case-insensitive. I don't have a Mac nearby to test whether case-only renames work...
    – ephemient
    Mar 24, 2009 at 22:39
  • Case-only rename on a default HFS+ volume on a Mac (10.5) doesn't work: "$ touch x && mv x X mv: x' and X' are the same file"
    – nobody
    Oct 9, 2009 at 20:23
1

I'd just use the find command to recur the subdirectories and mv to do the renaming, but still leverage Perl to get the renaming right.

find /foo/foo/documents -type f \
     -execdir bash -c 'mv "$0" \
                          "$(echo "$0" \
                              | perl -pe "s/\b([[:lower:]])/\u\$1/g; \
                                          s/\.(\w+)$/.\l\$1/;")"' \
              {} \;

Cryptic, but it works.

2
  • StackOverflow doesn't allow comments with less than 10 chars. All I wanted to say is: +1,geek.
    – Geo
    Mar 24, 2009 at 22:21
  • I'm embarrassed to have written it.
    – ashawley
    Mar 24, 2009 at 22:52
1

Another one:

find . -type f -exec perl -e'
  map {
        ( $p, $n, $s ) = m|(.*/)([^/]*)(\.[^.]*)$|;
        $n =~ s/(\w+)/ucfirst($1)/ge;
        rename $_, $p . $n . $s;
      } @ARGV
  ' {} +
0

Keep in mind that on case-remembering filesystems (FAT/NTFS), you'll need to rename the file to something else first, then to the case change. A direct rename from "etc.etc" to "Etc.Etc" will fail or be ignored, so you'll need to do two renames: "etc.etc" to "etc.etc~" then "etc.etc~" to "Etc.Etc", for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.