简体   繁体   中英

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.

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

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

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)

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