Functions to obtain (file_ext()), remove (sans_ext()), and
change (with_ext()) extensions in filenames.
Arguments
- x
A character of file paths.
- extra
Extra characters to be allowed in the extensions. By default, only alphanumeric characters are allowed (and also some special cases in ‘Details’). If other characters should be allowed, they can be specified in a character string, e.g.,
"-+!_#".- ext
A vector of new extensions. It must be either of length 1, or the same length as
x.
Details
file_ext() is similar to tools::file_ext(), and
sans_ext() is similar to tools::file_path_sans_ext().
The main differences are that they treat tar.(gz|bz2|xz) and
nb.html as extensions (but functions in the tools package
doesn't allow double extensions by default), and allow characters ~
and # to be present at the end of a filename.
Examples
library(xfun)
p = c("abc.doc", "def123.tex", "path/to/foo.Rmd", "backup.ppt~", "pkg.tar.xz")
file_ext(p)
#> [1] "doc" "tex" "Rmd" "ppt~" "tar.xz"
sans_ext(p)
#> [1] "abc" "def123" "path/to/foo" "backup" "pkg"
with_ext(p, ".txt")
#> [1] "abc.txt" "def123.txt" "path/to/foo.txt" "backup.txt"
#> [5] "pkg.txt"
with_ext(p, c(".ppt", ".sty", ".Rnw", "doc", "zip"))
#> [1] "abc.ppt" "def123.sty" "path/to/foo.Rnw" "backup.doc"
#> [5] "pkg.zip"
with_ext(p, "html")
#> [1] "abc.html" "def123.html" "path/to/foo.html" "backup.html"
#> [5] "pkg.html"
# allow for more characters in extensions
p = c("a.c++", "b.c--", "c.e##")
file_ext(p) # -/+/# not recognized by default
#> [1] "" "" ""
file_ext(p, extra = "-+#")
#> [1] "c++" "c--" "e##"