I have a script written in ruby. I need to remove any duplicate newlines (e.g.)
\n \n \n
to
\n
My current attempt worked (or rather not) using
str.gsub!(/\n\n/, "\n")
Which gave me no change to the output. What am I doing wrong?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With