繁体   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