-2

I have two files with the following format:

File1.txt

1
apple 1.056
ref 15

File2.txt

2
apple unknown
ref unknown1

How can I have the value for apple (1.056) from File1.txt be used in place of the what's written for File2.txt? I would like File2.txt to be updated to read:

2
apple 1.056
ref 15

I'm thinking a grep command may work but I'm unsure how to go about it. Any help will be much appreciated! Thanks

user7649922
  • 513
  • 1
  • 4
  • 9
  • Please explain the whole problem, cause now it is possible to get the result you want by just copying Fil1.txt to File2.txt and replace the first line. – klutt Mar 20 '17 at 20:20
  • Does file2 really have an unknown..unknownn column or is this just part of your example? – gregory Mar 20 '17 at 20:20
  • File1.txt and File2.txt can be structured very differently. apple from File1.txt may be on a different line than File2.txt – user7649922 Mar 20 '17 at 20:32
  • 1
    Btw: this works only because both files already sorted: `join --header file2 file1 -o 1.1,2.2` – Cyrus Mar 20 '17 at 20:55

1 Answers1

3

How can I have the value for apple (1.056) from File1.txt be used in place of the what's written for File2.txt? I would like File2.txt to be updated to read:

Straight forward awk which is repeated several times in fora, please search before posting.

Input

$ cat f1
1
apple 1.056
ref 15

$ cat f2
2
apple unknown
ref unknown1

Output

$ awk 'FNR==NR{a[$1]=$2;next}($1 in a){$2=a[$1]}1' f1 f2
2
apple 1.056
ref 15
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36
  • 1
    These problems will never fade away :) but still a good & working answer ++ – anubhava Mar 20 '17 at 20:29
  • Thanks Akshay Hegde.... The problem with this method is that it switches out all the common variables. What if I only want to change apple? How can I make this specific to key variables? – user7649922 Mar 20 '17 at 22:28
  • @user7649922 When you do not want to change ref, modify the requirements (example output). – Walter A Mar 20 '17 at 23:00