Rashid Rashid - 7 months ago 10
Bash Question

Copying values to properties in multiple files

I have file1.txt which contains:

PropertyA
PropertyB
PropertyC
PropertyD


I have another file named file2.txt which includes value for those parameters in file1.txt. So, file2.txt has parameters and values as follows:

PropertyA=valueforpropertyA
PropertyB=valueforpropertyB
PropertyC=valueforpropertyC
PropertyD=valueforpropertyD
PropertyE=valueforpropertyE
PropertyF=valueforpropertyF


The script needs to grab the values from file2.txt for the properties in file1.txt and write it to the file1.txt. Also, if there are no matching values for the properties it should ignore. Please see the below required output of file1.txt should look like:

PropertyA=valueforpropertyA
PropertyB=valueforpropertyB
PropertyC=valueforpropertyC
PropertyD=valueforpropertyD


Note: Values for PropertyE and PropertyF should be ignored because they are not declared in file1.txt.

Is there any way to check the comments and write to the file1.txt

File1.txt

PropertyA
PropertyB
PropertyC
####Some Comments##
PropertyA
PropertyB
PropertyC
PropertyD


The values in file2.txt should write the values for properties after the comments in file1.txt. It shouldn’t check the properties before the comment or shouldn’t write values for it. Output of file1:

PropertyA
PropertyB
PropertyC
####Some Comments##
PropertyA=valueforpropertyA
PropertyB=valueforpropertyB
PropertyC=valueforpropertyC
PropertyD=valueforpropertyD


How can this be done?

Answer

That can be solved using grep -f:

grep -Ff file1.txt file2.txt > _file1.txt && mv _file1.txt file1.txt

Update: After the question has been updated grep alone won't solve the problem. You can use following awk:

awk -F'=' 'FNR==NR{if (p) a[$0]; else {print; if ($0 ~ /####Some Comments##/) p=1} next}
  $1 in a' file1.txt file2.txt > _file1.txt && mv _file1.txt file1.txt

Output:

PropertyA
PropertyB
PropertyC
####Some Comments##
PropertyA=valueforpropertyA
PropertyB=valueforpropertyB
PropertyC=valueforpropertyC
PropertyD=valueforpropertyD