Reputation: 4861
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.
Upvotes: 0
Views: 2520
Reputation: 10625
For a regular expression, this should work, since * is greedy:
.*/
Upvotes: 0
Reputation: 14223
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"
Upvotes: 7
Reputation: 18484
You don't need a regex or split.
File.dirname("/foo/bar/baz.txt")
# => "/foo/bar"
Upvotes: 4
Reputation: 7729
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
Upvotes: 0
Reputation: 12618
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!
Upvotes: 1
Reputation: 176645
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'
Upvotes: 0