Using strsplit
we split the string into groups. Then remove everything up to the last \n
in the first group leaving its last line and paste that together with the second group:
groups <- strsplit(string, "\n\n+")[[1]]
paste(sub(".*\n", "", groups[1]), groups[2], sep = "\n\n")
giving:
[1] "third line\n\nFourth line\nFifth line"
Note that the above always puts two \n
between the last line of the first group and first line of the second group even if there were more originally. If its important to preserve the number of \n
then extract out the separators, seps
and from those choose the 1st that has more than 1 character. Use that in the final paste
:
seps <- strsplit(string, "[^\n]+")[[1]]
sep <- seps[nchar(seps) > 1][1] # 1st multiple \n separator
groups <- strsplit(string, "\n\n+")[[1]]
paste(sub(".*\n", "", groups[1]), groups[2], sep = sep)
REVISED Added note and improved slightly.