Comparing two files, if string exists in file 1, print 2 and if not print 1

Viewed 193

I have two files which I would like to compare. If string exists in file 1 (which only has one column), I would like to print a 2 next to it. If it only exists in file 2, I would like to print a 1 next to it. I want to keep all entries of file 2.

File 1:

5131885
5751191 

File 2:

5131885 1000019 -0.013936 0.0069218 -0.0048443 -0.0053688 0.0074161
5751191 1000046 -0.015001 0.0015263 0.00039903 0.0017072 -0.0021732
1668460 1000081 0.026323 0.0068929 0.0048965 0.0077047 0.0061728

File 3 (desired output):

5131885 2 1000019 -0.013936 0.0069218 -0.0048443 -0.0053688 0.0074161
5751191 2 1000046 -0.015001 0.0015263 0.00039903 0.0017072 -0.0021732
1668460 1 1000081 0.026323 0.0068929 0.0048965 0.0077047 0.0061728 

I tried to do it with awk, but I was not successful. I reached this point:

awk 'FNR==NR{arr[$1]=$1;next} ($1 in arr){print $0,arr[$1]}' file2 file1 > file3

But it does not add an extra column.

2 Answers

With your shown samples, please try following awk code.

awk 'FNR==NR{arr[$0];next} {$1=$1 OFS ($1 in arr?2:1)} 1' file1 file2

Explanation: Adding detailed explanation for above.

awk '              ##Starting awk program from here.
FNR==NR{           ##Checking condition if FNR==NR which will be TRUE when file1 is being read.
  arr[$0]          ##Creating arr with index of current line value here.
  next             ##next will skip all further statements from here.
}
{
  $1=($1 in arr)?$1 OFS 2:$1 OFS 1 ##Checking if $1 from file2 is present in arr then add 2 to it else add 1 to it.
}
1                  ##Printing current edited/non-edited line here.
' file1 file2      ##Mentioning Input_file names here.

OR a small variant of above solution as suggested by @Kaz in comments try following:

awk 'FNR==NR{arr[$0];next} $1=$1 OFS ($1 in arr?2:1)' file1 file2

Invert file1 and file2: Memorization of file1

Extract first field (k).

Remove first field (sub).

Detect k in memorized file1 for affect n (1 or 2).

print k, n and the rest of file2 line (without k).

awk 'FNR==NR{arr[$1]=$1;next} {k=$1; sub(/^[^ ]+ /, ""); n=1} (k in arr){n=2} {print k " " n " " $0}' file1 file2
Related