Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare lines of two files, print lines unique to first file [duplicate]

Tags:

bash

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
like image 256
Elliot Chance Avatar asked Jan 22 '13 02:01

Elliot Chance


2 Answers

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

like image 157
kojiro Avatar answered Nov 08 '22 21:11

kojiro


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.

like image 34
Rubens Avatar answered Nov 08 '22 19:11

Rubens