[英]Find strings and remove those lines
I'm trying to read all the text files from a directory, iterate through every file, and search for strings in the file and delete those lines. 我试图从目录中读取所有文本文件,遍历每个文件,然后在文件中搜索字符串并删除这些行。 Eg, 例如,
sample.txt sample.txt
#Wrote for the configuration ideas
mag = some , db\m09oi, id\polki
jio = red\po9i8
[\]
@mag = denk
@jio = tea
I want to delete the lines having mag. 我想删除具有mag的行。
Output 输出量
#Wrote for the configuration ideas
jio = red\po9i8
[\]
@jio = tea
I tried: 我试过了:
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
But the lines aren't removed. 但是这些行不会被删除。
Any suggestions please. 有任何建议请。
It is better to read the file line by line and if a line contains mag, just omit it, and only write other lines to the new file. 最好逐行读取文件,如果一行包含mag,则将其忽略,仅将其他行写入新文件。 — Credits to @WiktorStribiżew — 致谢@WiktorStribiżew
File.write(file_name, File.readlines(file_name).reject do |line|
line[/\bmag\b/]
end.join($/))
Here we read the file, split by lines with IO#readlines
, reject lines having mag
as a single word inside ( "magistrate"
won't be matched,) join it back with the line delimiter, specified for this particular platform (eg \\n
on unix) and write it back. 在这里,我们读取文件,并以IO#readlines
分隔行,拒绝包含mag
作为单个单词的行( "magistrate"
将不匹配,)与为此特定平台指定的行定界符(例如\\n
Unix上的\\n
)并将其写回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.