Home > database >  Remove character string only if it occurs at the end of a string
Remove character string only if it occurs at the end of a string

Time:04-22

I want to remove the final characters "txt" if they exist at the end of a character string. However, sometimes, the characters can be found at other locations of the string also.

i.e. I would like to remove txt from "/some-text-here/txt" but not from "/txt-not-to-remove-text/" since in the last example it does not occur after the last occurance of the /

So, I only want to extract txt if it occurs at the end of the string.

string = c("/some-text-here/txt",
           "/some-other-text-here/txt",
           "/txt-not-to-remove-text/",
           "/txt-another-line-of-text/txt")

CodePudding user response:

We may use trimws

trimws(string, whitespace = "/txt", which = 'right')

-output

[1] "/some-text-here"           "/some-other-text-here"  
[3]   "/txt-not-to-remove-text/"  "/txt-another-line-of-text"

Or using sub and specify the end ($) of the string

sub("/txt$", "", string)
  • Related