Yogendra Pratap Singh
Yogendra Pratap Singh

Reputation: 181

How to compare two text files for the same exact text using BASH Script?

Let's say I have two text files that I need to extract data out of. The text of the two files is as follows:

File1.txt

ami-1234567
ami-1234567654
ami-23456

File-2.txt

ami-1234567654
ami-23456
ami-2345678965

I want all the data of file2.txt which looks same from file1.txt.

Upvotes: 0

Views: 106

Answers (4)

michael
michael

Reputation: 9759

Just another option:

$ comm -1 -2  <(sort file1.txt) <(sort file2.txt)

The options specify that "unique" limes from first file (-1) and second file (-2) should be omitted.

This is basically the same as

$ join <(sort file1.txt) <(sort file2.txt)

Note that the sorting in both examples happens without creating an intermediate temp file, if you don't want to bother creating one.

Upvotes: 1

Fravadona
Fravadona

Reputation: 16905

Did you try join?

join -o 0 File1.txt File2.txt
ami-1234567654
ami-23456

remark: For join to work correctly, it needs your files to be sorted, which seems to be the case with your sample.

Upvotes: 1

This is litteratly my first comment so I hope it works,

but you can try using diff:

diff file1.txt file2.txt

Upvotes: 1

lunaferie
lunaferie

Reputation: 401

I don`t know if I proper understand You:

but You can Try sort this files (after extract):

 sort file1 > file1.sorted
 sort file2 > file2.sorted

Upvotes: 0

Related Questions