I have a file with specific numbers in a column and I want to extract lines which have those numbers in column 3 from another file.

For example, I have extract.file with:


And input.file with

1 AB 123 home 123
1 AC 568 cat 568
1 BC 689 dog 123
1 BB 456 car 456

And I want an outcome file with only:

1 AB 123 home 
1 BC 689 dog
1 BB 456 car

I used

grep -wF -f extract.file input.file > output.file

But this includes the last column too:

1 BC 689 dog 123

So how can I search only in column 3 and exclude the last column from output?


One way:

awk 'NR==FNR{a[$1];next}($3 in a){$NF="";print;}' extract.file input.file

To get the whole line without removing the last column:

awk 'NR==FNR{a[$1];next}($3 in a)' extract.file input.file
  • Thank you, I think it works, is there also a way to use this if I want to delete the lines with the specific numbers in the input file. So to get an output file where the lines with numbers in column 3 are not present any more?
    – Nicole
    Dec 21 '16 at 10:24
  • Sorry, it did not work completely, by using the command I am missing the last column of each line in the output file (the input file has lines with column ranging about the 2000)
    – Nicole
    Dec 21 '16 at 10:34
  • "So how can I search only in column 3 and exclude the last column from output?" Your requirement was to exclude the last column
    – Guru
    Dec 21 '16 at 10:38
  • Ah sorry, I meant not get the the line who has the word in another column! So only the lines who has the word in the 3th column. Can you help me adjust the script so I get the whole line?
    – Nicole
    Dec 21 '16 at 11:22
  • Updated the solution
    – Guru
    Dec 21 '16 at 11:39

use regular expression in your pattern file:

[0-9]\+ [A-Z]\+ 123
[0-9]\+ [A-Z]\+ 689
[0-9]\+ [A-Z]\+ 456

grep -f   extract.file input.file
1 AB 123 home 123
1 BC 689 dog 123
1 BB 456 car 456
  • Thank you. The files are however not that simple as I made it and around 1.6 GB. I do not have that extra information in the extract.file and can only get it from the input.file. So in order to get that I still need to extract the specific lines...
    – Nicole
    Dec 21 '16 at 9:58
  • why can't you add that preceeding regex constant in extract.file using sed or awk? Dec 21 '16 at 10:02

You could use cut:

grep -wF -f extract.file input.file | cut -d" "  -f1,2,3,4  >  output.file

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.