Replace variable value in first file based on records in second

Hello ,

I have below files
a) File A

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root xmlns="http://aaa/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema" version="2.0">
    <project name="source">
        <mapping name="m_Source">
            <parameter name="SQL_Query">select  * from $$SCHEMA_NAME."$$TABLE_NAME" where $$COL > $$VALUE and $CONDITIONS</parameter>
            <parameter name="CONDITIONS">Default</parameter>
        </mapping>
    </project>
</root>

b) File b

$$SCHEMA_NAME=test
$$COL=LOAD_DATETIME
$$TABLE_NAME=table1
$$VALUE=1234

I want to replace the values of $$SCHEMA_NAME , $$COL , $$TABLE_NAME, $$VALUE with the values mentioned in right ( i.e. test,DATETIME,table1,1234) in file a

thanks for your help!!

You may use sed:

sed -r -i -e 's/$$SCHEMA_NAME/test/' yourfile.xml

if your SCHEMA_NAME is in the shell variable 'schema', you can use this:

sed -r -i -e 's/$$SCHEMA_NAME/'"$schema/" yourfile.xml

Watch out to see the quotings right!

you may use more than one Parameter -e 's/search/replace/' in one command.

The selection of $$IDENTIFIER is a bit harder to manage since $ is a special character which is used in the shell vor substituting variables. So it must be quoted properly to work. A better choice may be to use %%IDENTIFIER%%.

And regarding this one...

$$SCHEMA_NAME=test
$$COL=LOAD_DATETIME
$$TABLE_NAME=table1
$$VALUE=1234

If you think this is a correct shell variable assignment: It's not. correctly you would use:

SCHEMA_NAME=test
COL=LOAD_DATETIME
TABLE_NAME=table1
VALUE=1234

Access of the value of a variable is done via one $ - character:

echo $SCHEMA_NAME
1 Like

If you have bash version 4:

#!/bin/bash
# bash version 4 required

# associative array
declare -A AR

# read file into array
while IFS="=" read key val
do
  AR[$key]=$val
done < FileB
# now process the main input file, IFS= = keep leading spaces
while IFS= read -r line
do
  # cycle through each key
  for key in "${!AR[@]}"
  do
    val=${AR[$key]}
    # substitute key with value, // = globally = try many times
    line=${line//$key/$val}
  done
  echo "$line"
done < FileA
2 Likes

How about

sed -f <(sed 's/^/s=/; s/$/=/' file2) file1
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root xmlns="http://aaa/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema" version="2.0">
    <project name="source">
        <mapping name="m_Source">
            <parameter name="SQL_Query">select  * from test."table1" where LOAD_DATETIME > 1234 and $CONDITIONS</parameter>
            <parameter name="CONDITIONS">Default</parameter>
        </mapping>
    </project>
 </root>

EDIT: or

sed 's/^/s=/; s/$/=/' file2 | sed -f- file1
3 Likes