2013-03-25 52 views
2

我意有所指浏览StackOverflow上每一个解决方案,似乎没有任何要删除空行的从文本文件,该文件是这样的:文件Ruby的空行不会删除

google 
yahoo 

facebook 

reddit 

除其他来源,我已经试过:

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

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

然而,这些都没有工作。我正在撕裂我的头发,似乎没有原生的Nokogiri方法,正则表达式也不起作用。

+1

删除所有空行试试这个:line.gsub(“\ n”,“”) – 2013-03-25 20:28:45

+0

你肯定没有空间?试试m模式。尝试'line.gsub(/^\ s * $/m,'')' – knut 2013-03-25 20:33:42

回答

0

更改GSUB一点点,它会工作

File.foreach("file.txt"){|line| 
    line.gsub("\n", '') 
} 
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 
2

你怎么样检查它是否是空的呢?

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

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

哇不知道为什么我没有想过用chomp – engineersmnky 2013-03-25 20:42:46

+0

@engineersmnky只要保持简单吧:)? – squiguy 2013-03-25 20:43:24

0

String#squeeze对此很好。在这里,它将一系列的线端减少到单线端。

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

我用一个衬垫下面从文件

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