簡體   English   中英

Ruby從文件中刪除包含空格的空行

[英]Ruby remove blank lines from a file which include spaces

我正在嘗試從文件中刪除空白行。

我當前的代碼是:

 def remove_blank_lines_from_file(file)
   File.write(file, File.read(file).gsub(/^$\n/, '')) 
 end

上面的代碼僅刪除了空行,但我也想刪除包含空格的行。

我該怎么辦?

由於您仍然將整個文件加載到內存中,因此可能更易於閱讀:

File.write(file, File.readlines(file).reject { |s| s.strip.empty? }.join)

只需刪除那些僅包含空格的行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM