Search for a Keyword in file and replace another keyword or add at the end of line

Hi

I want to implement something like this:

if( keyword1 exists)
then
check if(keyword2 exists in the same line)
then replace keyword 2 with New_Keyword
else
Add New_Keyword at the end of line
end if

eg:

Check for Keyword JUNGLE and add/replace VALUES(TIGER,LION):
Here JUNGLE is Keyword1 and VALUES is Keyword2 and VALUES(TIGER,LION) is New_Keyword.

Lines in INPUT File

JUNGLE Hello WORLD VALUES(DEER,WOLF),
RIVER Hello WORLD,
JUNGLE Hello WORLD, 

In Line 1, we can have any values inside ().
Expected OUTPUT File

JUNGLE Hello WORLD VALUES(TIGER,LION),
RIVER Hello WORLD,
JUNGLE Hello WORLD VALUES(TIGER,LION),

In Line 1, we over write the existing values.
In Line 3, we added values at the end.
In Line 2, no changes required and keyword JUNGLE is missing in the line.

Let me know if more clarity is required.

awk '$0 ~ /JUNGLE/ {if($0 ~ /VALUES/) {sub("VALUES.*", "VALUES(TIGER,LION)")} else {sub("$", "VALUES(TIGER,LION)") }}1' file

Hi
When I am running the below code I m not getting the desired output.

awk '$0 ~ /$key1/ {if($0 ~ /COMPRESS/) {sub("COMPRESS.*",$key2)} else {sub("$",$key2) }}1' FILENAME.txt

However if I am hardcoding the variable values it is giving desired output.

 awk '$0 ~ /HELLO/ {if($0 ~ /COMPRESS/) {sub("COMPRESS.*",HI)} else {sub("$",HI) }}1' FILENAME.txt

Any way by which i can use variables here.

shell and awk variable are altogether different. try something like

awk -v pattern=$key1 '$0 ~ pattern {if($0 ~ /COMPRES/ ..........

Here, pattern is an awk variable.

tried this. still not working.

awk -v var1=$key1, -v var2=$key2 '$0 ~ /var1/ {if($0 ~ /COMPRESS/) {sub("COMPRESS.*",var2)} else {sub("$",var2) }}1' FILENAME.txt

try removing '/' around var1

awk -v var1=$key1, -v var2=$key2 '$0 ~ var1 {if($0 ~ /COMPRESS/) {sub("COMPRESS.*",var2)} else {sub("$",var2) }}1' FILENAME.txt
$ awk '$0 ~ search {(/\(.*)/)?gsub(/\(.*)/,"("replace")"): gsub(/\,$/," VALUES("replace")&")}1' search="JUNGLE" replace="TIGER,LION" file

JUNGLE Hello WORLD VALUES(TIGER,LION),
RIVER Hello WORLD,
JUNGLE Hello WORLD VALUES(TIGER,LION),

Try also

awk '$0 ~ KW1 {sub (",$","");sub (" *"KW2".*$", ""); $0=$0 " " NKW ","} 1' KW1=JUNGLE KW2=VALUES NKW="VALUES(TIGER,LION)" file
JUNGLE Hello WORLD VALUES(TIGER,LION),
RIVER Hello WORLD,
JUNGLE Hello WORLD VALUES(TIGER,LION),