Find particular file in particular directory

-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?

Prakash V Holkar

Posted 2014-04-29T07:07:55.320

Reputation: 119

@ Dave Rook - abc.uploaded is the file name – Prakash V Holkar – 2014-04-29T07:20:04.077

Answers

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

Dave

Posted 2014-04-29T07:07:55.320

Reputation: 24 199

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 – Prakash V Holkar – 2014-04-29T07:38:51.457

So, the name abc could be anything? If so, the code above will work! – Dave – 2014-04-29T07:40:25.577

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? – Prakash V Holkar – 2014-04-29T07:44:58.667

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? – Dave – 2014-04-29T07:47:24.257

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

Prakash V Holkar

Posted 2014-04-29T07:07:55.320

Reputation: 119