Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a difference file by specific patterns in two text files

I have 2 text files and I need to export "changes" to a new file. That means that the second file's rows are compared to the first file's rows and if a row isn't found there, then it will append it to the new (third) file.

Contents of the first file are:

ABC 123 q1w2sd
DEF 321 sdajkn
GHI 123 jsdnaj
JKL 456 jsd223

The second file contains:

ABC 123 XXXXXX
JKL 456 jsd223
DEF XXX sdajkn
GHI 123 jsdnaj

Notice that lines which start with ABC and DEF have changed. JKL has just changed it's place.

The output file should contain: ABC 123 XXXXXX DEF XXX sdajkn

How to do this using 'awk' or 'sed'?

Edit: Also new lines in the second file should be counted as changes..

like image 904
Dropout Avatar asked Jan 13 '23 01:01

Dropout


2 Answers

awk 'NR == FNR { f1[$0]; next } !($0 in f1)' file1 file2

With grep: grep -Fvxf file1 file2

like image 156
Dimitre Radoulov Avatar answered Jan 15 '23 16:01

Dimitre Radoulov


Assuming 1st file is named: fileA and 2nd file is named: fileB you can use awk like this:

awk 'NR==FNR {a[$1];b[$0];next} ($1 in a) && !($0 in b)' file{A,B}

OR simply:

awk 'NR==FNR {a[$1];b[$0];next} ($1 in a) && !($0 in b)' file1 file2
like image 40
anubhava Avatar answered Jan 15 '23 15:01

anubhava