I'm on a windows box, and I'm using basename to extract file names from some directories. Apparently, there is a limit to the size that a file name can be, otherwise basename throws an error (earlier I was on a linux and there I don't remember a [roblem, and from a quick glance at the source code it looks like basename is different for different systems - so this is quite likely not a reproducible example on linux or osx).
Anyway, I am wrapping basename in a tryCatch and would like to just capture the last chunk of the filename when there is an error. How can I do this?
Example to follow:
filename <- paste0("c:/some directory/", paste(rep("abc ", 100), collapse=""), ".txt")
basename(filename)
# Error in basename(filename) : path too long
So, I do a tryCatch,
value <- tryCatch(basename(filename), error=function(e) e)
str(value)
# $ message: chr "path too long"
# $ call : language basename(filename)
# - attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
But, how could I get, say just the last 30 characters of the filename, instead of just an error message?
Better math here than in the comment. I don't get an error like you said, so I will make one
filename <- paste0("c:/some directory/", paste(rep("abc ", 100), collapse=""), ".txt")
basename(filename)
value <- tryCatch(simpleError(), error=function(e)
substring(filename, nchar(filename) - 29, nchar(filename)))
str(value)
# chr "c abc abc abc abc abc abc .txt"
or
value <- tryCatch(simpleError(), error=function(e)
gsub('(.{30}$)|.', '\\1', filename))
str(value)
# chr "c abc abc abc abc abc abc .txt"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With