文件中的Ruby空行赢得';移开 我必须浏览StAccess中的每一个解决方案,似乎没有什么东西能从这样的文本文件中删除空白行: google yahoo facebook reddit

文件中的Ruby空行赢得';移开 我必须浏览StAccess中的每一个解决方案,似乎没有什么东西能从这样的文本文件中删除空白行: google yahoo facebook reddit,ruby,line,gsub,Ruby,Line,Gsub,在其他来源中,我尝试过: File.foreach("file.txt") { |line| line.gsub(/^$\n/, '') } 及 然而,这些都不起作用。我在胡思乱想,似乎没有原生的Nokogiri方法,正则表达式也不起作用。稍微更改一下gsub,它就会起作用 File.foreach("file.txt"){|line| line.gsub("\n", '') } source_file='/hello.txt' new_file=file.new('/hello_n

在其他来源中,我尝试过:

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


然而,这些都不起作用。我在胡思乱想,似乎没有原生的Nokogiri方法,正则表达式也不起作用。

稍微更改一下gsub,它就会起作用

File.foreach("file.txt"){|line|
  line.gsub("\n", '')
}
source_file='/hello.txt'
new_file=file.new('/hello_new.txt'))
文件::打开(新的_文件,'w')do |文件|
文件::打开(源_文件,'r')。每个(sep=“\n”)do |行|

文件你检查一下它是否为空怎么样

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

File.foreach("file.txt") { |line|
  out.puts line unless line.chomp.empty?
}
这很好。在这里,它将一系列线端减少为一个线端

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

open(“out.txt”、“w”){| out | open(“test.txt”){| in | out我使用下面一行删除文件中的所有空行

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

试试这个:line.gsub(“\n”,”)你确定没有空格吗?也试试m模式。试试
line.gsub(/^\s*$/m),)
open("out.txt", "w") {|out| open("test.txt") {|in| out << in.read.squeeze("\n")}}
file = "/tmp/hello.log"
File.write(file, File.read(file).gsub(/\n+/,"\n"))