3

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.

4

5 回答 5

2

我在一个衬里下使用从文件中删除所有空行

file = "/tmp/hello.log"
File.write(file, File.read(file).gsub(/\n+/,"\n"))
于 2015-01-11T16:19:46.600 回答
2

您如何检查它是否为空?

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

File.foreach("file.txt") { |line|
  out.puts line unless line.chomp.empty?
}
于 2013-03-25T20:41:47.277 回答
0

String#squeeze很适合这个。在这里,它将一系列线路末端减少为单个线路末端。

open("out.txt", "w") {|out| open("test.txt") {|in| out << in.read.squeeze("\n")}}
于 2013-03-25T21:37:00.520 回答
0

稍微改变一下 gsub 就可以了

File.foreach("file.txt"){|line|
  line.gsub("\n", '')
}
于 2013-03-25T20:33:38.397 回答
0
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
于 2013-03-25T20:36:08.000 回答