How to replace multiple newlines in a row with one newline using Ruby How to replace multiple newlines in a row with one newline using Ruby ruby ruby

How to replace multiple newlines in a row with one newline using Ruby


This works for me:

#!/usr/bin/ruby$s = "foo\n\n\nbar\nbaz\n\n\nquux";puts $s$s.gsub!(/[\n]+/, "\n");puts $s


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"


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"