Lin Ma
Lin Ma

Reputation: 10139

find lines in one file but not in another file in Linux Shell

I have two files, one line is a string. I want to find lines in the first file, but not in the 2nd file. No matter what is the order (line number where the string exists). There are no duplicate lines inside one file. Wondering the shell command in Linux?

BTW, if there is a way to find common lines of the two files, it will be great as well. :)

For example,

file 1,

hello
world
python
java
scala

file 2,

hello
python
C++
C
Go

I want to output,

world
java
scala

thanks in advance, Lin

Upvotes: 3

Views: 3220

Answers (2)

ncenerar
ncenerar

Reputation: 1537

I've had the same problem and here is how I solved it (for reference) :

sort file1 file2        | uniq -d > common_lines
sort file1 common_lines | uniq -u > file1_uniq_lines

or in oneline:

sort file1 <(sort file1 file2 | uniq -d) | uniq -u > file1_uniq_lines

Upvotes: 1

William Pursell
William Pursell

Reputation: 212248

I think this is what you want.

grep -f file.2 -v file.1

(It works for the example you give, but does not actually do what I interpret your question as asking, but the question is not clear so my interpretation may be completely wrong.)

Upvotes: 6

Related Questions