Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

ruby - How to read a file's content and search for a string in multiple files

I have a text file that has around 100 plus entries like out.txt:

domain1esrt
domain2345p
yrtfj
tkpdp
....
....

I have to read out.txt, line-by-line and check whether the strings like "domain1esrt" are present in any of the files under a different directory. If present delete only that string occurrence and save the file.

I know how to read a file line-by-line and also know how to grep for a string in multiple files in a directory but I'm not sure how to join those two to achieve my above requirement.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can create an array with all the words or strings you want to find and then delete/replace:

strings_to_delete = ['aaa', 'domain1esrt', 'delete_me']

Then to read the file and use map to create an array with all the lines who doesn't match with none of the elements in the array created before:

# read the file 'text.txt'
lines = File.open('text.txt', 'r').map do|line|
  # unless the line matches with some value on the strings_to_delete array
  line unless strings_to_delete.any? do |word| 
    word == line.strip 
  end
  # then remove the nil elements
end.reject(&:nil?)

And then open the file again but this time to write on it, all the lines which didn't match with the values in the strings_to_delete array:

File.open('text.txt', 'w') do |line|
  lines.each do |element|
    line.write element
  end
end

The txt file looks like:

aaa
domain1esrt
domain2345p
yrtfj
tkpdp
....
....
delete_me

I don't know how it'll work with a bigger file, anyways, I hope it helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...