[英]Ruby remove blank lines from a file which include spaces
I am trying to remove blank lines from a file. 我正在尝试从文件中删除空白行。
My current code is: 我当前的代码是:
def remove_blank_lines_from_file(file)
File.write(file, File.read(file).gsub(/^$\n/, ''))
end
The above code removes only the empty lines, but I also want to remove the lines which include spaces. 上面的代码仅删除了空行,但我也想删除包含空格的行。
How could I do it? 我该怎么办?
Since you nevertheless load the whole file into memory, this might be easier to read: 由于您仍然将整个文件加载到内存中,因此可能更易于阅读:
File.write(file, File.readlines(file).reject { |s| s.strip.empty? }.join)
Just remove those lines, containing the spaces only. 只需删除那些仅包含空格的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.