18

I have two text files that contain a unique sorted list of words:

File 1:

a
b
c
d

File 2:

b
c

I need a new file that contains only the extraneous lines in File 1, so the result will be

a
d
jww
  • 97,681
  • 90
  • 411
  • 885
Elliot Chance
  • 5,526
  • 10
  • 49
  • 80

3 Answers3

23

This is what comm is for:

comm -- select or reject lines common to two files

You want

comm -23 "File 1" "File 2"

which will suppress output of lines only in file 2 and lines in both files, leaving only lines in file 1. More answers here on Greg Wooledge's wiki

kojiro
  • 74,557
  • 19
  • 143
  • 201
7

You can use grep:

grep -f file1.txt -vFx file2.txt

Notice the usage of the flags F, --fixed-strings and x, --line-regexp, to force the comparison to be performed considering the entire line.

Rubens
  • 14,478
  • 11
  • 63
  • 92
  • 2
    Thanks, this also works: `sort file1.txt file2.txt file2.txt | uniq -u` – Elliot Chance Jan 22 '13 at 02:26
  • This answer doesn't require files to be sorted. More human-readable: `grep -f file1.txt --fixed-strings --line-regexp --invert-match file2.txt` – d9k Feb 20 '22 at 11:16
3

Try this

$ join file1.txt file2.txt -v 1

$ man join

-a FILENUM
   print unpairable lines coming from file FILENUM, where FILENUM is 1 or 2, corresponding to FILE1 or FILE2
-v FILENUM
   like -a FILENUM, but suppress joined output lines
Alessandro
  • 2,378
  • 2
  • 15
  • 13