user3188544
user3188544

Reputation: 1631

How to match and remove whole lines from a file in ruby?

I have two files:

  1. Phrases.txt
  2. Phrases-to-exclude.txt

Both files has a phrase on each line like this:

some phrase 1
some phrase 2
some phrase 3

Is there a way I can remove all the lines that are in the "Phrases to exclude" file from the main "Phrases" file?

The phrases are exact -- so only the entire line needs to be matched.

Upvotes: 1

Views: 69

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118271

You can do as below also :

data_from_main_file = File.readlines('Phrases.txt')
data_to_exclude = File.readlines('Phrases-to-exclude.txt')
File.write('output.txt', (data_from_main_file - data_to_exclude).join)

Upvotes: 0

Dorian
Dorian

Reputation: 23939

phrases = File.read('Phrases.txt').lines
exclude = File.read('Phrases-to-exclude.txt').lines

File.write('Result.txt', (phrases - exclude).join)

Upvotes: 3

Related Questions