andilabs
andilabs

Reputation: 23341

get filename from url path in R

I would like to extract filename from url in R. For now I do it as follows, but maybe it can be done shorter like in python. assuming path is just string.

path="http://www.exanple.com/foo/bar/fooXbar.xls"

in R:

tail(strsplit(path,"[/]")[[1]],1)

in Python:

path.split("/")[-1:]

Maybe some sub, gsub solution?

Upvotes: 7

Views: 4248

Answers (2)

Simon O'Hanlon
Simon O'Hanlon

Reputation: 59990

There's a function for that...

basename(path)
[1] "fooXbar.xls"

Upvotes: 26

Justin
Justin

Reputation: 43265

@SimonO101 has the most robust answer IMO, but some other options:

Since regular expressions are greedy, you can use that to your advantage

sub('.*/', '', path)
# [1] "fooXbar.xls"

Also, you shouldn't need the [] around the / in your strsplit.

> tail(strsplit(path,"/")[[1]],1)
[1] "fooXbar.xls"

Upvotes: 1

Related Questions