-1

I want to find the particular file name in particular directory in ruby.

I tried the following Dir.glob()

file = Dir.glob("/home/prakash/Desktop/*.uploaded") 

output:

/home/prakash/Desktop/abc.uploaded 

But I just want only the file name in output. I don't want file name with fully path.

So how can I do this?

1
  • @ Dave Rook - abc.uploaded is the file name Commented Apr 29, 2014 at 7:20

2 Answers 2

0

In Ruby, there is a file class.

File.basename("/home/prakash/Desktop/abc.uploaded") 

The above will return abc.uploaded

Since I'm not sure if you want the extention or not, you can remove it using

File.basename("/home/prakash/Desktop/abc.uploaded", ".uploaded") 

The above will return abc

More reading

Or you could perform a string manipulation

'/home/prakash/Desktop/abc.uploaded'.split('\\').last 
4
  • Actually I don't know the file name on particular directory, I just know the extension of that file i.e. .uploaded, by using this extension i want to find the file name only without full path in prefix Commented Apr 29, 2014 at 7:38
  • So, the name abc could be anything? If so, the code above will work! Commented Apr 29, 2014 at 7:40
  • yes name abc could be anything. In you code you have given the fully path upto fine name to "File.basename()" class. But i don't know the file name, I know only the file extension then how can i do? Commented Apr 29, 2014 at 7:44
  • I'm sorry, I'm still a little lost - why don't you know the file name? If Dir.glob(... is returning the full path, then you do know it? Commented Apr 29, 2014 at 7:47
0

I got easy way to find only file name without full path:

file = Dir.glob("/file/path/*.uploaded").join(" ") filename = file.split('/').last 

And it's working great for me

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.