Skip to content

Instantly share code, notes, and snippets.

@joethorley
Last active August 29, 2015 13:56
Show Gist options
  • Save joethorley/9199214 to your computer and use it in GitHub Desktop.
Save joethorley/9199214 to your computer and use it in GitHub Desktop.

Revisions

  1. joethorley revised this gist Feb 24, 2014. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions ext.R
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,6 @@
    library(tools)
    library(assertthat)

    #' @title Filename extension utilities
    #'
    #' @description Replaces, adds or removes (rm) extensions from filenames or test whether
  2. joethorley created this gist Feb 24, 2014.
    70 changes: 70 additions & 0 deletions ext.R
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    #' @title Filename extension utilities
    #'
    #' @description Replaces, adds or removes (rm) extensions from filenames or test whether
    #' filename has an extension or is a filename with a particular extension.
    #' Functions are primarily wrappers
    #' on the tools package functions \code{file_ext} and \code{file_path_sans_ext}.
    #'
    #' @usage
    #' get_ext(x)
    #' has_ext(x)
    #' is_ext(x, ext)
    #' rm_ext(x)
    #' replace_ext(x, ext)
    #' add_ext(x, ext)
    #'
    #' @param x a character vector of the filenames.
    #' @param ext a character scalar of the extension with or without a leading point.
    #' @return A character vector of the extensions or modified filenames or a logical vector
    #' indicating whether a filename has an extension or is a particular extension.
    #' @seealso \code{\link{file_ext}} and \code{\link{file_path_sans_ext}}
    #' @aliases has_ext is_ext rm_ext replace_ext add_ext
    #' @examples
    #'
    #' x <- c("file", "file.txt", "file.txt.zip")
    #' get_ext(x)
    #' has_ext(x)
    #' is_ext(x, "txt")
    #' is_ext(x, ".txt")
    #' rm_ext(x)
    #' replace_ext(x, "md")
    #' add_ext(x, "md")
    #' @export
    get_ext <- function (x) {
    file_ext(x)
    }

    rm_leading_dot <- function (x) {
    sub("^[.]", "", x)
    }

    #' @export
    has_ext <- function (x) {
    get_ext(x) != ""
    }

    #' @export
    is_ext <- function (x, ext) {
    assert_that(is.string(ext))
    ext <- rm_leading_dot (ext)
    get_ext(x) == ext
    }

    #' @export
    rm_ext <- function (x) {
    file_path_sans_ext(x)
    }

    #' @export
    replace_ext <- function (x, ext) {
    assert_that(is.string(ext))
    ext <- rm_leading_dot (ext)
    paste(rm_ext(x), ext, sep = ".")
    }

    #' @export
    add_ext <- function (x, ext) {
    assert_that(is.string(ext))
    ext <- rm_leading_dot (ext)
    paste(x, ext, sep = ".")
    }