Delete text after final period in line

I have a grep puzzle that eludes me: I would like to delete text after the last period in the string collection (I use R, so perl syntax is available).

For example, let's say that the string is ABCD.txt , this grep will return ABCD , and if the text was abc.com.foo.bar , it will return abc.com.foo .

Any help with respect was appreciated (I don't think I can drink more coffee!).

+4
source share
4 answers

Here are some solutions:

 > sub("^(.*)[.].*", "\\1", "abc.com.foo.bar") # 1 [1] "abc.com.foo" > sub("[.][^.]*", "", "abc.com.foo.bar") # 2 [1] "abc.foo.bar" > library(tools) > file_path_sans_ext("abc.com.foo.bar") # 3 [1] "abc.com.foo" 

ADDED. As for your comment asking to remove the leading periods, the easiest way is to simply pass this to any of the above, where x is the input line:

 sub("^[.]*", "", x) 

To make any of them in one line:

 > x <- c("abc.com.foo.bar", ".abc.com.foo.bar", ".vimrc") > > sub("^[.]*(.*)[.]?.*$", "\\1", x) # 1a [1] "abc.com.foo.bar" "abc.com.foo.bar" "vimrc" > > gsub("^[.]*|[.][^.]*$", "", x, perl = TRUE) # 2a [1] "abc.com.foo" "abc.com.foo" "vimrc" > > file_path_sans_ext(sub("^[.]*", "", x)) # 3s [1] "abc.com.foo" "abc.com.foo" "vimrc" 
+7
source

And a modeless answer for no reason:

 test <- c("abc.com.foo.bar","ABCD.txt") sapply(strsplit(test,"\\."), function(x) paste0(head(x,-1),collapse=".") ) #[1] "abc.com.foo" "ABCD" 
+3
source

You can use sub for example, for example:

 sub('(.*)[.](.*)','\\1',c('abc.com.foo.bar','ABCD.txt')) [1] "abc.com.foo" "ABCD" 
+2
source

I can't help you with r, and I almost forgot perl, but it works in both JS ( proof ) and PHP

 /\.[A-Za-z]+$/ --> replace this with empty string "" ^ ^ ^ | | | | | end of line | only chars (you can add 0-9 if numbers are also present) dot before last chars 

regex syntax is pretty common, so I'm sure you can accept it (maybe just get rid of /

+1
source

Source: https://habr.com/ru/post/1493331/


All Articles