Get a difference file for specific patterns in two text files

I have 2 text files and I need to export the “changes” to a new file. This means that the lines of the second file are compared with the first lines of the file, and if the line is not found there, then it will add it to the new (third) file.

The contents of the first file:

  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

Note that lines starting with ABC and DEF have changed. JKL just changed his 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 considered as changes.

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

With grep: grep -Fvxf file1 file2

+4
source

Suppose the first file is named: fileA and the second file is named: fileB you can use awk as follows:

 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 
+3
source

Code for GNU :

  $ sed 's # \ (. * \) # / \ 1 / d #' file1 | sed -f - file2
 ABC 123 XXXXXX
 DEF XXX sdajkn

This also applies to newlines in file2 .

+2
source

Using comm to find lines in the second file that are not in the first:

 $ comm -13 <(sort first) <(sort second) ABC 123 XXXXXX DEF XXX sdajkn 
0
source

Source: https://habr.com/ru/post/1488114/


All Articles