Skip to main content
2 of 3
added 353 characters in body
Stéphane Chazelas
  • 584.8k
  • 96
  • 1.1k
  • 1.7k

Here's another way:

grep -vFxf new.txt old.txt >> new.txt 

The -v flag tells grep to print lines that do NOT match the pattern given, and the -f new.txt tells grep to use the lines in the file new.txt as the pattern to search for. With -F, the patterns are Fixed strings instead of basic regular expressions and with -x, they have to match the full lines. So grep -vFxf new.txt old.txt means "show me all lines in old.txt that are missing from new.txt".

We append those lines to new.txt using the >> redirection operator. Note that new.txt is used here both as input and as input, but grep will read the full initial content of new.txt to build the list of strings to search and stop reading it after that, so extra lines printed afterwards to new.txt won't be read again.

terdon
  • 252.3k
  • 69
  • 480
  • 718