Awk command to left/right outer join 2 files

Viewed 40

File1 contains 2 rows :

/home/asingh549/cleanup,8  
/home/vbhat94/test_bkup,8

File2 contains 3 rows :

/home/asingh549/cleanup,7  
/home/vbhat94/test_bkup,7  
/home/asingh699/sample/adam,1

Expected output :

/home/asingh549/cleanup,8  
/home/vbhat94/test_bkup,8  
/home/asingh699/sample/adam,1

I tried -

awk -F, 'NR==FNR{a[$1]=$2; next} {print $1 FS a[$1] }' File1 File2

but I get below output -

/home/asingh549/cleanup,8  
/home/vbhat94/test_bkup,8 
/home/asingh699/sample/adam,

The 3rd line of the output is missing number 1 after the comma.
Could someone please advice how can I get the desired output?

4 Answers

You may use this awk solution:

awk '
BEGIN {FS=OFS=","}
FNR == NR {
   map[$1] = $2
   next
}
$1 in map {
   $2 = map[$1]
}
1' file1 file2

/home/asingh549/cleanup,8
/home/vbhat94/test_bkup,8
/home/asingh699/sample/adam,1

Your code might be amoleriated to get desired output as follows

awk -F, 'NR==FNR{a[$1]=$2; next} {print $1 FS (($1 in a)?a[$1]:$2) }' File1 File2

then output changes to

/home/asingh549/cleanup,8
/home/vbhat94/test_bkup,8
/home/asingh699/sample/adam,1

Explanation: I use so-called ternary operator condition?valueiftrue:valueiffalse, check $1 in a is check if array a has given key.

(tested in gawk 4.2.1)

If this is the wrong answer, I apologise in advance, however...

cat file1 > file3
sed -n '3p' file2 >> file3

If you need to know how to do this with variable line numbers in future, than you can use '$p' in order to always print the last line of a file, even when you don't know what its' number is.

{m,g}awk -F, 'NR==FNR ? _*(___[$!_]=$_) : \
              $!NF = _<(__=___[$!_]) ? __ : $_' f1.txt f2.txt
/home/asingh549/cleanup,8  
/home/vbhat94/test_bkup,8
/home/asingh699/sample/adam,1
Related