简体   繁体   中英

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

#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.

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. Credits to @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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM