# Split a path into its components

Share:

### Description

decompose_path splits a path into the directory name, filename without extension, and extension. strip_extension, get_extension and replace_extension provide shortcuts to manipulate the file extension. recompose_path takes the result of decompose_path and returns complete paths.

### Usage

  1 2 3 4 5 6 7 8 9 10 11 12 decompose_path(x = dir()) get_extension(x = dir()) recompose_path(x, ...) ## S3 method for class 'decomposed_path' recompose_path(x, ...) replace_extension(x = dir(), new_extension, include_dir = NA) strip_extension(x = dir(), include_dir = NA) 

### Arguments

 x A character vector of file paths. Defaults to files in the current directory. ... Not currently used. new_extension A new extension to replace the existing ones. include_dir Should the directory part of the path be included? If NA, the default, keep the directory from the input. If TRUE, standardize the directory. If FALSE, strip the directory.

### Value

decompose_path returns a character matrix with three columns named "dirname", "filename" and "extension". strip_extension returns a character vector of the filename, possibly with a directory (see include_dir argument). replace_extension returns a character vector of the filename with a newextension, possibly with a directory (see include_dir argument). get_extension returns a character vector of the third column. recompose_path returns a character vector of paths.

### Warning

A few of the tests for this function don't pass under the CRAN Windows machine. It is unclear exactly why this is happening, and the failing tests have not been reproduced elsewhere. If you have unexpected behaviour with this function, please report it on the package issue tracker. https://github.com/richierocks/pathological/issues

### Note

Decomposing and then recomposing a path is usually equivalent to standardizing that path (though slower). That is, usually recompose_path(decompose_path(x)) == standardize_path(x). One exception to this is when the directory of x is a symbolic link to another directory. In this case decompose_path will follow the link but standardize_path won't.

file_ext, a primitive version of get_extension
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 x <- c( "somedir/foo.tgz", # single extension "another dir\\bar.tar.gz", # double extension "baz", # no extension "quux. quuux.tbz2", # single ext, dots in filename R.home(), # a dir "~", # another dir "~/quuuux.tar.xz", # a file in a dir "", # empty ".", # current dir "..", # parent dir NA_character_ # missing ) (decomposed <- decompose_path(x)) get_extension(x) strip_extension(x) strip_extension(x, FALSE) recompose_path(decomposed)