[英]Custom setter method won't accept blank values in Ruby on Rails?
[英]Ruby blank line in file won't remove
我一定在瀏覽StackOverflow上的每個解決方案,似乎沒有任何東西從文本文件中刪除空白行,如下所示:
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方法,正則表達式也不起作用。
你怎么檢查它是否是空的?
out = File.new("out.txt", "w")
File.foreach("file.txt") { |line|
out.puts line unless line.chomp.empty?
}
我使用下面的一個襯墊刪除文件中的所有空行
file = "/tmp/hello.log"
File.write(file, File.read(file).gsub(/\n+/,"\n"))
稍微更改gsub就可以了
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對此很好。 在這里,它將一系列線端減少到一個線端。
open("out.txt", "w") {|out| open("test.txt") {|in| out << in.read.squeeze("\n")}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.