0

how can I read input from first file say file1.txt and print column 3 $3 from file2.txt if first file $1 is equal to $2 in second file?

if '$1 in file1.txt == $1 in file file2.txt {print $3 from file2.txt}' 

I couldn't find simple and straight forward solution to question?

Monalizza
  • 43
  • 5
  • possible duplicate of [Using AWK to Process Input from Multiple Files](http://stackoverflow.com/questions/14984340/using-awk-to-process-input-from-multiple-files) – paddy Jul 27 '15 at 05:33
  • Fairly closely related, but not identical to my way of thinking. – Jonathan Leffler Jul 27 '15 at 06:41

1 Answers1

3

It's pretty straight-forward:

awk 'FNR == NR { a[FNR] = $1; next }
     FNR != NR { if (a[FNR] == $2) print $3 }' file1.txt file2.txt

The first line saves the value of $1 for each line in file1.txt (and skips the rest of the script).

The second line doesn't formally need the FNR!=NR condition, but I think it makes it clearer. It processes file2.txt. If the value in $2 is equal to the corresponding saved value, print $3.

If the files are too big to save the $1 values from file1.txt in memory, you should have said so and you have to work harder. It can still be done with awk; it just isn't as neat and tidy and awk-ish.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • but the files have to have the same number of lines?? because in my case file1.txt is just a subset of file2.txt so that after saving the values in $1 then I need to compare it with all of the second files $1 values ?? – Monalizza Jul 27 '15 at 09:30
  • Then I think you have misstated the problem you want solved, probably by accident. Do you mean: _How can I read the values from column 1 of `file1.txt` and then for `file2.txt`, print the value in column 3 if the value in column 2 matches any of the values from column 1 in the first file?_. If so, then `awk 'FNR==NR{a[$1]=1;next}{if ($2 in a)print $3}'` should do the job unless I mistyped something. – Jonathan Leffler Jul 27 '15 at 12:28