Tutorial :Cut off the filename and extension of a given string


I build a little script that parses a directory for files of a given filetype and stores the location (including the filename) in an array. This look like this:

def getFiles(directory)    arr = Dir[directory + '/**/*.plt']    arr.each do |k|      puts "#{k}"    end  end  

The output is the path and the files. But I want only the path.

Instead of /foo/bar.txt I want only the /foo/

My first thought was a regexp but I am not sure how to do that.


Could File.dirname be of any use?

File.dirname(file_name ) â†' dir_name

Returns all components of the filename given in file_name except the last one. The filename must be formed using forward slashes (``/’’) regardless of the separator used on the local file system.

File.dirname("/home/gumby/work/ruby.rb") #=> "/home/gumby/work"  


You don't need a regex or split.

File.dirname("/foo/bar/baz.txt")  # => "/foo/bar"  


The following code should work (tested in the ruby console):

>> path = "/foo/bar/file.txt"  => "/foo/bar/file.txt"  >> path[0..path.rindex('/')]  => "/foo/bar/"  

rindex finds the index of the last occurrence of substring. Here is the documentation http://docs.huihoo.com/api/ruby/core/1.8.4/classes/String.html#M001461

Good luck!


I would split it into an array by the slashes, then remove the last element (the filename), then join it into a string again.

path = '/foo/bar.txt'    path = path.split '/'  path.pop  path = path.join '/'    # path is now '/foo'  


not sure what language your in but here is the regex for the last / to the end of the string.


Transliterates to all characters that are not '/' before the end of the string


For a regular expression, this should work, since * is greedy:


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »