September 12, 2006

Change Filename Extension

Below is a utility that I find myself using very often for batch scripts which read an input file, and save the output to files with same filename but different extension (e.g. "file.log" -> "file.csv")

#
# filename_change_extension "/dir/file.txt", ".CSV"
# => "/dir/file.CSV"
#
# filename_change_extension "/dir/file",     ".CSV"
# => "/dir/file.CSV"
#

def filename_change_extension( filename, extension )
    filename =~ /(.*[\/\\])?    # match the path, up to the last slash
        ([^\/\\]+)              # match the filename (no slashes)
        $                       # up to the end of string
        /x                      # remove comments from regexp
    path, name = ($1 || ""), $2 # if no path given, use "" instead of nil
    ext      = File.extname(name)
    basename = File.basename(name, ext )
    
    return path + basename + extension 
end


if __FILE__ == $0

    require "test/unit"
    
    class TestFilenameChangeExtension < Test::Unit::TestCase
        def test_1
            test_cases = [
                [   "filename",               ".c" , "filename.c"],
                [   ".filename",              ".c" , ".filename.c"],
                [   ".a.b.c.ext",             ".c" , ".a.b.c.c"],
                [   "filename.ext",           "s"  , "filenames"],
                [   "filename.ext",           ""   , "filename"],
                [   "/dir/dir2/filename.txt", ".c" , "/dir/dir2/filename.c"],
                [   "/dir/dir2/filename",     ".c" , "/dir/dir2/filename.c"],
                [   "/dir/dir2/.filename",    ".c" , "/dir/dir2/.filename.c"],
                [   "/dir2.with.dot/filename",".c" , "/dir2.with.dot/filename.c"],
            ]
    
            test_cases.each{|filename, extension, expected|
                assert_equal expected, filename_change_extension( filename, extension) , 
                             "test case [#{filename.inspect}, #{extension.inspect}]" 
            }
        end
    end

end

Posted by laza at 04:54 PM | Comments (0) | TrackBack

September 06, 2006

Photos

Little Paul is doing great, thanks for asking. All of you who wanted pictures, here they are:

http://lazax.com/photos/Pavle/

I will try to keep adding new pictures weekly.

Posted by laza at 12:33 AM | Comments (0) | TrackBack