Reconcile data in separate files

I have several questions of this type, and I really tried to solve this problem myself.

I have two data files; I want to compare their first fields and print a line from the second file next to the corresponding entry from the first file in the output file. It is important to preserve the order of the list in file 1, including strings without matches. Files have values ​​separated by tabs, but I can change them if necessary (although the data uses commas).

file1.txt

37600
39219
32887
01262
69241
00361
34180
42385
69245

file2.txt

37600       GEAR PUMP   1
32887       MOTOR, 480V 1
34180       BRACKET 2
00361       WASHER  4
42385       SCREW       8

Desired Output File

37600       GEAR PUMP   1
39219
32887       MOTOR, 480V 1
01262
69241
00361       WASHER  4
34180       BRACKET 2
42385       SCREW       8
69245

This is my best effort so far, but it leads to empty files.

awk NR==NFR{a[$1];next}$1 in a {print $0} file1.txt file2.txt > outfile.txt

Any help would be greatly appreciated.

+4
source share
2 answers

, awk .

awk 'FNR==NR {a[$1]=$0;next} a[$0] {$0=a[$0]}1' file2 file1
37600       GEAR PUMP   1
39219
32887       MOTOR, 480V 1
01262
69241
00361       WASHER  4
34180       BRACKET 2
42385       SCREW       8
69245

file2 $1 .
file1 , $0 .


, , #1 :

awk 'FNR==NR {a[$1]=$0;next} a[$1] {$0=a[$1]}1' file2 file1
+3

join:

join -1 2 -2 1 -a1 <(cat -n file1.txt | sort -k2,2) <(sort file2.txt) | sort -k2 | cut --complement -d" " -f2

37600 GEAR PUMP 1
39219
32887 MOTOR, 480V 1
01262
69241
00361 WASHER 4
34180 BRACKET 2
42385 SCREW 8
69245

@devnul, .

+2

All Articles