pierrefevrier
pierrefevrier

Reputation: 1650

Find and replace variables with SED in a file

I'd would like to find and replace variables in a conf file in KSH (with SED). My question is: what is the correct regex pattern to identify KSH variables (like $toto or ${toto}), by taking into account that variable's name can contains special characters ?

Here is an example:

Let's say I have var_1=value1 and var_2=value2 in my current shell (grepable in export -p).

The configuration file before find and replace

PARAM1=$var_1/tata.txt
PARAM2=${var_2}/tata.txt

The configuration file after find and replace

PARAM1=value1/tata.txt
PARAM2=value2/tata.txt

What I have to do:

  1. Find $var_1 and ${var_2} in then conf file (with generic regex, I suppose I don't know if there are variables in the conf file)
  2. Search value of each with export -p | grep var_1 and export -p | grep var_2
  3. Replace these 2 variables in conf file by the value found by previous search

Thank you for your answers.

Upvotes: 0

Views: 604

Answers (4)

anubhava
anubhava

Reputation: 786091

You can try this one-liner workaround:

cat config
PARAM1=$var_1/tata.txt
PARAM2=${var_2}/tata.txt

( export var_1=value1; export var_2=value2; bash -x ./config 2>&1 >/dev/null|sed 's/^+ //' )
PARAM1=value1/tata.txt
PARAM2=value2/tata.txt

Upvotes: 0

NeronLeVelu
NeronLeVelu

Reputation: 10039

Src=/tmp/sed.Source
FIn=/tmp/sed.In
FOut=/tmp/sed.Out

# take all variable as source but could be reduce (highly recommended)
set > ${Src}

cp YourFile ${FIn}
sed 's/=/ /' ${Src} | while read vName vValue
 do
   sed "s/\$$vName/$vValue/g;s/\${$vName}/$vValue/g" ${FIn} > ${FOut}
   mv ${Fout} ${FIn}
 done

#rm ${Src}
cat ${Fin}
#rm ${Fin}

Main concern is when content (value) of the variable contain regex specail char like /.* so not the best solution for that

could be done in sed only wit a preload of variable value and a marker than recursive replacement

Upvotes: 0

devnull
devnull

Reputation: 123648

This is one those cases where the evil and dangerous eval would come in handy:

while read line; do
  eval echo "$line"
done < inputfile > outputfile

Upvotes: 1

Jotne
Jotne

Reputation: 41460

Using awk (I do see you are asking for sed)

awk '{gsub(/\${?var_1}?/,x);gsub(/\${?var_2}?/,y)}1' x="$var_1" y="$var_2" file
PARAM1=value1/tata.txt
PARAM2=value2/tata.txt

Upvotes: 0

Related Questions