I am trying to compare the data in two files, one which has columns and then wish to print the data that is found in both

File 1:



itemA item1
itemB item2
itemC item3

Hence i would like to compare File 1 with column 2 of File 2, if they are identical I would like to display the entire line.

For example if file1 contains:


and file2 contains:

dataA data1
dataC data3

would only display:

dataA data1

as this is the line in file2 with the data item in file1

Many Thanks in advance

1 Answer 1


Use grep:

grep -Fwf file1 file2

from man grep:

-F, --fixed-strings
    Interpret PATTERN as a list  of  fixed  strings  (instead  of  regular  expressions),  separated  by
    newlines, any of which is to be matched.

-f FILE, --file=FILE
    Obtain patterns from FILE, one per line.  If this option is used multiple times or is combined  with
    the -e (--regexp) option, search for all patterns given.  The empty file contains zero patterns, and
    therefore matches nothing.

-w, --word-regexp
    Select only those lines containing matches that form whole words.  The test  is  that  the  matching
    substring  must  either  be  at  the  beginning  of  the line, or preceded by a non-word constituent
    character.  Similarly, it must be either  at  the  end  of  the  line  or  followed  by  a  non-word
    constituent character.  Word-constituent characters are letters, digits, and the underscore.

Or awk:

awk 'NR==FNR{seen[$0]++} ($2 in seen)' file1 file2

At above, first we are reading the file1 and holds the entire column1 from into an array named seen, then look in file2 on its second column and if it's matched with the saved column1 from file1 then goes to print entire row of file2.

You also have join command if both files are sorted (if not, you can pass sorted output by sorting):

join -1 1 -2 2 file1 file2

from man join

      join on this FIELD of file 1

      join on this FIELD of file 2

if files are not sorted:

join -1 1 -2 2 <(sort file1) <(sort file2)
  • Hi AFSHIN i am currently trying the awk command is it meant to print out data to the command line?
    – Tom Apter
    Aug 11, 2017 at 10:43
  • 1
    Cheers that worked, and will do :)
    – Tom Apter
    Aug 11, 2017 at 10:49
  • 1
    The grep command can give you false positive matches since you haven't constrained it to match at the end.
    – user218374
    Aug 11, 2017 at 12:08
  • @RakeshSharma correct, but we are assuming file1 data only and only will present in column2 of file2. Aug 11, 2017 at 17:58

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.