Home > Back-end >  Script for combining changes in key value pairs
Script for combining changes in key value pairs

Time:04-28

I want to combine 2 files which contains key value pairs for string localizations. I should keep added values from file 1, and rewrite updated values from file 2.

File 1:

"cart.title" = "Cart";
"cart.subtitle" = "Price";

"checkout.title" = "Checkout";

File 2:

"cart.title" = "Cart";

"checkout.title" = "Super checkout;

Desired result:

"cart.title" = "Cart";
"cart.subtitle" = "Price";

"checkout.title" = "Super checkout";

I have tried it with awk, but problem is that it always moves new strings from file 1 to end of file. And I want to keep my strings grouped as original file.

awk -F= '!a[$1]  ' 2.strings 1.strings > results.strings

But I am struggling to maintain original order and result looks like this:

"cart.title" = "Cart";

"checkout.title" = "Super Checkout";
"cart.subtitle" = "Price";

I think that it should be pretty easy task for anyone who's domain is Linux. Thanks in advance.

CodePudding user response:

With your shown samples and attempts, please try following awk code.

awk '
FNR==NR{
  arr1[$1]=$0
  arr2[  count]=$1
  next
}
($1 in arr1){
  arr1[$1]=$0
}
END{
  for(i=1;i<=count;i  ){
    print arr1[arr2[i]]
  }
}
' file1 file2

Explanation: Adding detailed explanation for above code.

awk '                       ##Starting awk program from here.
FNR==NR{                    ##Checking condition which will be TRUE when file1 is being read.
  arr1[$1]=$0               ##Creating arr1 with index of $1 and value of $0.
  arr2[  count]=$1          ##Creating arr2 with index of   count and value of $0.
  next                      ##next will skip all further statements from here.
}
($1 in arr1){               ##Checking condition if $1 is in arr1 then do following.
  arr1[$1]=$0               ##Setting arr1 value to $0 with index of $1.
}
END{                        ##Starting END block of this program from here.
  for(i=1;i<=count;i  ){    ##Starting a for loop from 1 to till value of count.
    print arr1[arr2[i]]     ##Printing value of arr1 with index of arr2 here.
  }
}
' file1 file2               ##Mentioning Input_file names here.
  • Related