2013-03-25 118 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"))