简体   繁体   中英

Ruby blank line in file won't remove

I must've browsed every solution on StackOverflow, nothing seems to be removing the blank line's from text file which looks like this:

google
yahoo

facebook

reddit

Amongst other sources, I've tried:

File.foreach("file.txt") { |line|
  line.gsub(/^$\n/, '')
}

and

replace = text.gsub /^$\n/, ''
File.open("file.txt", "w") { |file| file.puts replace }

However, these aren't working. I'm tearing my hair out, it seems that there is no native Nokogiri method, and regular expressions aren't working either.

How about you check if it is empty instead?

out = File.new("out.txt", "w")

File.foreach("file.txt") { |line|
  out.puts line unless line.chomp.empty?
}

I use below one liner to delete all blank lines from a file

file = "/tmp/hello.log"
File.write(file, File.read(file).gsub(/\n+/,"\n"))

Change the gsub a little bit and it will work

File.foreach("file.txt"){|line|
  line.gsub("\n", '')
}
source_file = '/hello.txt'
new_file = File.new('/hello_new.txt')
File::open(new_file,'w') do |file|
  File::open(source_file,'r').each(sep="\n") do |line|
    file << line unless line.gsub("\n",'').length == 0
  end
end

String#squeeze is nice for this. Here it reduces series of line-ends to a single line-end.

open("out.txt", "w") {|out| open("test.txt") {|in| out << in.read.squeeze("\n")}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM