0

I have four files like so:

File 1 contents (tab separated, 3 columns):

applepen apple pen
strawberry straw berry

File 2 contents:

applepen
strawjelly

File 3 contents(This file is sorted):

apple
fan
straw

File 4 contents(This file is sorted):

pen
zenith

I need to compare field 1 of file 1 with file 2, field 2 of file 1 with file 3 and field 3 of file 1 with file 4. If all three matches are found, I want to print field 1,2,3 of file 1. I want to do this for each line in file 1.

The output here should be:

applepen apple pen

Is there any way to do this using grep or comm or something similar?

  • field 1,2,3 of file 1 -- but file 1 only has one field – Jeff Schaller Nov 7 '16 at 12:03
  • @JeffSchaller Sorry. I've fixed it now. – user199046 Nov 8 '16 at 3:21
0
while read -r f11 f12 f13
do
  grep -qxFe "$f11" file2 && 
  grep -qxFe "$f12" file3 && 
  grep -qxFe "$f13" file4 && 
  printf "%s\n" "$f11 $f12 $f13"
done < file1
1

This is a task for join.

$ cat file1 
applepen    apple   pen
strawberry  straw   berry
$ cat file2
applepen
strawjelly
$ cat file3
apple
fan
straw
$ cat file4
pen
zenith
$ join file[12] | join -1 2 -o 1.1,1.2,1.3 - file3 | join -1 3 -o 1.1,1.2,1.3 - file4
applepen apple pen
$ 

If you really care about the tabs instead of spaces, you can translate them back with | tr ' ' '\t'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy