-2

I'm wondering how to implement function which will find and replace string in my bash script, eg:

#!/bin/bash
if [ $1 -eq 1 ] then
ListToReplace="'Static_value as Column1','Static_value2' as Column2"
Searching which query contain Column1, Column2 , then Somehow replace in queries...
else
do nothing.
fi

query="Select Column1, Column2 from dual"
run query
query2="Select Column3, Column1 from dual"
run query2

let's assume we will run script with variable 1, then query should look:

Select 'Static_value' as Column1,'Static_value2' as Column2  from dual

and query2:

Select Column3, Static_value as Column1 from dual

with variable 0 then:

Select Column1,Column2  from dual
Select Column3,Column1 from dual

Any hints? Thanks

Dummy00001
  • 16,630
  • 5
  • 41
  • 63
bazyl
  • 263
  • 1
  • 7
  • 17

1 Answers1

1

Replacement in the bash is quite simple, though I'm not sure why you need/want a list here:

#!/bin/bash

query="Select Column1, Column2 from dual"
query2="Select Column3, Column1 from dual"

if [ "${1:-0}" -eq 1 ]; then
    for VAR in query query2; do
        VAL=${!VAR}
        VAL=${VAL/Column1/Static_value as Column1}
        VAL=${VAL/Column2/\'Static_value2\' as Column2}
        eval $VAR=\$VAL
    done
fi

echo run $query
echo run $query2

The VAL=${!VAR} reads variable's value by name. The eval $VAR=\$VAL assigns variable's value by name. (See here for more.) The ${//} expansion performs the replacement inside the value.

Community
  • 1
  • 1
Dummy00001
  • 16,630
  • 5
  • 41
  • 63