0

I would like to compare two files find common lines between column 1 of each file and print out the full line (multiple columns) of file 1.

file1:

a   apple
c   cat
e   eagle
f   fire
g   green   
h   horse   
i   igloo
j   jack

and

file2:

b
c
d
e
f

I would expect the output to be as:

c   cat
e   eagle
f   fire

Any help is much appreciated.

4

This is a job for coreutils :-)

If the files are already sorted and have the common field in the first column:

$ join file1 file2
c cat
e eagle
f fire

If your files aren't sorted:

join <(sort file1) <(sort file2)
  • 1
    Also, the -j 1 is not needed as the default join key is the first column of each file. – Kusalananda Aug 21 at 7:21
0
$ awk 'NR==FNR { a[$1]++ ; next}; $1 in a' file2 file1
c   cat
e   eagle
f   fire

This reads in file2 (the first filename argument) and stores it in array a. It detects whether it is reading the first file by checking whether NR (the total number of input records seen so far) is equal to FNR (the input record number of the current input file)

Then it reads file1 (the second filename argument) and if the first field is in array a, it prints the matching input line (in awk, the default action on any successful test result, such as $1 in a, is to print the input line - so $1 in a by itself is equivalent to $1 in a {print}).


BTW, in many cases, tasks like this can be done with grep -f file2 file1 but that will match the contents of file2 anywhere in file1 - e.g. c from file2 would match not only cat but also jack in file1.

0

A solution using grep's -f option with the help of sed (as suggested by cas):

$ grep -f <(sed 's/^/^/' file2) file1
c   cat
e   eagle
f   fire

Command sed 's/^/^/' file2 adds a caret ^ to the start of each line in file2. We use this output as pattern input file for grep's -f option using a process substitution (<(…)).

The grep command prints those lines in file1 matching the patterns of the command substitution. We need the ^ character in our patterns to match those lines which are starting with the given character.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.