簡體   English   中英

查找字符串並刪除那些行

[英]Find strings and remove those lines

我試圖從目錄中讀取所有文本文件,遍歷每個文件,然后在文件中搜索字符串並刪除這些行。 例如,

sample.txt

#Wrote for the configuration ideas

mag = some , db\m09oi, id\polki
jio = red\po9i8

[\]

@mag = denk
@jio = tea

我想刪除具有mag的行。

輸出量

#Wrote for the configuration ideas

jio = red\po9i8

[\]

@jio = tea

我試過了:

Dir.glob("D:\\my_folder\\*.txt") do |file_name|

  value = File.read(file_name)
  change = value.gsub!(/[@m]ag/, "")
  File.open(file_name, "w") { |file| file.puts change }

end

但是這些行不會被刪除。

有任何建議請。

最好逐行讀取文件,如果一行包含mag,則將其忽略,僅將其他行寫入新文件。 致謝@WiktorStribiżew

File.write(file_name, File.readlines(file_name).reject do |line|
                        line[/\bmag\b/]
                      end.join($/))

在這里,我們讀取文件,並以IO#readlines分隔行,拒絕包含mag作為單個單詞的行( "magistrate"將不匹配,)與為此特定平台指定的行定界符(例如\\n Unix上的\\n )並將其寫回。

暫無
暫無

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

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