62

How to remove all line breaks (enter symbols) from the string?

my_string <- "foo\nbar\rbaz\r\nquux"

I've tried gsub("\n", "", my_string), but it doesn't work, because new line and line break aren't equal.

Toto
  • 89,455
  • 62
  • 89
  • 125
Marta
  • 3,493
  • 6
  • 28
  • 43

4 Answers4

113

You need to strip \r and \n to remove carriage returns and new lines.

x <- "foo\nbar\rbaz\r\nquux"
gsub("[\r\n]", "", x)
## [1] "foobarbazquux"

Or

library(stringr)
str_replace_all(x, "[\r\n]" , "")
## [1] "foobarbazquux"
Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
21

I just wanted to note here that if you want to insert spaces where you found newlines the best option is to use the following:

gsub("\r?\n|\r", " ", x)

which will insert only one space regardless whether the text contains \r\n, \n or \r.

Midnighter
  • 3,771
  • 2
  • 29
  • 43
  • 1
    This is a nice and complete answer. I like the `\r\n` touch. Note that one can use `trimws(x, "right")` to quickly trim off newline and carriage returns if they appear only at the end of `x`. This will, of course, trim trailing spaces, tabs, etc. – Geoffrey Poole Apr 14 '18 at 08:03
0

Have had success with:

gsub("\\\n", "", x)
cmoez
  • 1
  • 1
0

With stringr::str_remove_all

library(stringr)
str_remove_all(my_string, "[\r\n]")
# [1] "foobarbazquux"
Julien
  • 1,613
  • 1
  • 10
  • 26