I have a script written in ruby. I need to remove any duplicate newlines (e.g.)
\\n
\\n
\\n
to
\\n
My current
Try This It Worked for me:
s = test\n\n\nbar\n\n\nfooo
s.gsub("\n\n", '')
Use the more idiomatic String#squeeze
instead of gsub
.
str = "a\n\n\nb\n\n\n\n\n\nc"
str.squeeze("\n") # => "a\nb\nc"
Simply calling split will also trim out all of your whitespace.
You need to pass \n
to split
>> "one ok \ntwo\n\nthree\n".split(/\n+/).join("\n")
=> "one ok \ntwo\nthree"
Additionally, also works with
str.gsub! /\n^\s*\n/, "\n\n"
where,
Simply splitting and recombining the lines will give the desired result
>> "one\ntwo\n\nthree\n".split.join("\n")
=> "one\ntwo\nthree"
Edit: I just noticed this will replace ALL whitespace substrings with newlines, e.g.
>> "one two three\n".split.join("\n")
=> "one\ntwo\nthree"
First check that this is what you want!
are you sure it shouldn't be /\n\n\n/, "\n" that what you seem to be wanting in your question above.
also, are you sure it's not doing a windows new-line "\r\n"?
EDIT: Additional info
Per Comment
"The amount of newlines can change. Different lines have between 2 and 5 newlines."
if you only want to hit the 2-5 lines try this
/\n{2,5}/, "\n"