I have two files: File 1 an input file with 191 lines in only a column. File 2 is a master file with 712 lines in 2 columns.

Output = find the match between Input_File and the first column of Master_File, then print the line of the matching rows in Master_File.

Input_File Sample:


Master_File Sample:

945713 Ignavibacterium_album_JCM_16511_uid162097
521045 Kosmotoga_olearia_TBF_19_5_1_uid59205
1254432 Sorangium_cellulosum_So0157_2_uid210741
1144275 Corallococcus_coralloides_DSM_2259_uid157997
59374 Fibrobacter_succinogenes_S85_uid41169
741091 Rahnella_Y9602_uid62715
83332 Mycobacterium_tuberculosis_H37Rv_uid57777
103690 Nostoc_PCC_7120_uid57803
115713 Chlamydophila_pneumoniae_CWL029_uid57811
158879 Staphylococcus_aureus_N315_uid57837

I tried using grep in for loops:

for i in $(cat Input_File); do grep $i Master_File; done

But this command searched for the match in both columns in Master_File.

I know how to print only the first column with awk but the purpose of printing the matching lines is to obtain the second column information in Master_File.

Is there anyway to use awk in printing the first column of Master_File, find the matches using for loops by referring to Input_File and print the row that match from Master_File?

Or any suggestion for an easier way to command?


try this awk command

awk 'NR==FNR{Arr[$0]++;next}{if($1 in Arr){print $0}}' input_file master_file

read the input file and keep the contents into Array and iterate the second file and check the first column value is in array. if its present in array, then print the master_file line

  • Thanks! It worked! Btw, I did found an alternative command somewhere as below: grep -f Input_File Master_File Both the commands provided same output on the file I was testing. Any idea on the difference between these two commands? – web Apr 16 at 4:33
  • Also, what if I need to repeat this command with another Master_File that are separated by a comma instead of a space. Do I need to specify the FS in this case? If yes, then how? – web Apr 16 at 4:53

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.